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..a7cd7986c4 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -469,6 +469,60 @@ fn visual_bounds_include_stroke() { assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5))); } +/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its +/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed +/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing. +#[test] +fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() { + use crate::appearance::LineCap; + use vectorcraft_geom::{Point, SubPath}; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let node = |closed: bool, cap: LineCap| { + let mut subpaths = square.subpaths.clone(); + subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed)); + let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art()); + let s = p.appearance.stroke_mut().unwrap(); + (s.cap, s.join) = (cap, crate::appearance::LineJoin::Round); + p + }; + for closed in [false, true] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let p = node(closed, cap); + let geometric = p.geometric_bounds().unwrap(); + let visual = p.visual_bounds().unwrap(); + assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor"); + let dot = closed && cap != LineCap::Butt; + assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}"); + assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor"); + } + } +} + +/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's +/// width round the anchor under every join, miter and bevel joins included, which measure the +/// stroke along its segments. +#[test] +fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() { + use crate::appearance::{LineCap, LineJoin}; + use vectorcraft_geom::{Point, SubPath}; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let mut subpaths = square.subpaths.clone(); + subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true)); + let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art()); + let s = p.appearance.stroke_mut().unwrap(); + (s.cap, s.join, s.width) = (cap, join, 4.0); + let visual = p.visual_bounds().unwrap(); + if cap == LineCap::Butt { + assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing"); + } else { + assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach"); + } + } + } +} + /// A group's box from its members' boxes grows by the group's own strokes, leaves out members /// without a box, and is `None` when none has one. #[test] diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 0178af8460..d72048dc0a 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -17,15 +17,16 @@ //! other stop there, showing their previews). use std::borrow::Cow; +use std::cell::Cell; use std::collections::BTreeSet; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_geom::{Affine, PathData, Rect, SubPath}; -use vectorcraft_color::Paint; +use vectorcraft_color::{Color, Paint}; -use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; +use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; /// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or /// an EPS file's art, shown as one locked object. @@ -123,12 +124,27 @@ impl PlacedDocument { } /// The art the object shows, as plain objects with `n`'s id: one group, its resources named - /// as [`Document::with_placed_art`] adds them (nothing until that has read it). + /// as [`Document::with_placed_art`] adds them (nothing until that has read it). While + /// [`Crossed`] is on for this thread, its box crossed from corner to corner instead + /// ([`Self::crossed_art`]). pub fn art(&self, n: &Node) -> Vec { + if crossed() { + return vec![self.crossed_art(n)]; + } let prefix = prefix(&self.key); read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect() } + /// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the + /// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document + /// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art. + pub fn crossed_art(&self, n: &Node) -> Node { + let q = self.corners(); + let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]); + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))]) + } + /// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with /// `prefix`. fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option { @@ -470,6 +486,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc>) -> Option = const { Cell::new(false) }; +} + +/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed +/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the +/// file's art when made with `false`; once dropped, the setting before it applies again. A +/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images +/// in Outline Mode, so that effects and live objects make their art from the crossed box. +#[must_use] +pub struct Crossed(bool); + +impl Crossed { + pub fn set(on: bool) -> Self { + Self(CROSSED.with(|c| c.replace(on))) + } +} + +impl Drop for Crossed { + fn drop(&mut self) { + CROSSED.with(|c| c.set(self.0)); + } +} + +/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]). +pub fn crossed() -> bool { + CROSSED.with(Cell::get) +} + /// `p`'s file as read already (else its preview's), without reading it. pub fn read_cached(p: &PlacedDocument) -> Option> { let mut c = cache(); diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 8115d00954..9509690a59 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -291,9 +291,12 @@ impl StrokeLayer { // past them are measured. match self.body_along(&segs, side, out) { Some(body) => out = out.union(body), - // A subpath with no length paints at most its caps' dot. + // A subpath with no length paints at most its caps' dot. A closed subpath with + // no segment, a lone anchor, has its dot at that anchor under a round or + // projecting cap. None if !butt => { - let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)); + let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p)); + let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone); out = dot.map_or(out, |d| out.union(d.inflate(side, side))); } None => {} diff --git a/crates/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/newart.rs b/crates/engine/src/cmd/newart.rs index ffea03187d..f43221120c 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -286,9 +286,9 @@ impl Session { return; } let read = self.read_selection_paints(); - let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed)); + let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed(), p.stroke_mixed())); let (fill, stroke) = self.proxy_paints(); - let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed); + let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed()); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. if !fill_mixed && !self.tool_paints(false) { @@ -323,7 +323,7 @@ impl Session { Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) }); } let paints = st.selection_paints()?.clone(); - (!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints) + (!paints.in_live_paint() && self.fill_mesh_points().is_empty()).then_some(paints) } } diff --git a/crates/engine/src/cmd/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..3669068ab0 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -51,7 +51,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -238,9 +238,11 @@ impl Session { } // A Live Paint group without faces (or edges) shows the next selected object's paint; any other // object without a painted object shows the defaults for new art. A face or edge selected with - // its Live Paint group counts with the group, wherever it is in the selection. - let covered = st.selection_live_paint_covered(st.selection.subjects()); - for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) { + // its Live Paint group counts with the group, wherever it is in the selection. A targeted + // layer stands for its selected editable art, which the paint commands edit + // (ItemTarget::targets), not for a locked or hidden object in it. + let covered = st.selection_live_paint_covered(&st.selection.objects); + for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, stroke, &mut nodes); @@ -316,7 +318,7 @@ impl Session { .into_iter() .filter(|id| editable(&id)) .collect(); - return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| { + return targets.iter().zip(row.each_target(self, &targets)).find_map(|(id, at)| { let n = st.doc.node(*id)?; of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?) }); @@ -396,20 +398,62 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' /// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or /// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a /// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with -/// [`SelectionPaints::add`]. +/// [`SelectionPaints::add`], and the objects taken out of it with [`SelectionPaints::remove`]. #[derive(Clone, Debug, Default)] pub(crate) struct SelectionPaints { - fill: Option, - pub(crate) fill_mixed: bool, - stroke: Option, - pub(crate) stroke_mixed: bool, - weight: Option, - pub(crate) weight_mixed: bool, - /// An object is a face or edge of a Live Paint group, or lies inside one + fill: Tally, + stroke: Tally, + weight: Tally, + /// The objects that are a face or edge of a Live Paint group, or lie inside one /// ([`live_paint_covered`]). - pub(crate) in_live_paint: bool, - /// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]). - pub(crate) may_hold_mesh: bool, + in_live_paint: usize, + /// The objects that are a gradient mesh or a container ([`Session::fill_mesh_points`]). + may_hold_mesh: usize, +} + +/// The first value met, how many of the values met are the same as it, and how many were met. +#[derive(Clone, Debug)] +struct Tally { + first: Option, + same: usize, + all: usize, +} + +impl Default for Tally { + fn default() -> Self { + Self { first: None, same: 0, all: 0 } + } +} + +impl Tally { + fn add(&mut self, value: T, same: impl Fn(&T, &T) -> bool) { + self.all += 1; + match &self.first { + Some(f) if same(f, &value) => self.same += 1, + Some(_) => {} + None => (self.first, self.same) = (Some(value), 1), + } + } + /// Take out a value met before. → false when the values left must be met again to know which + /// differ: every value the same as the first one is gone, and others are left. + fn remove(&mut self, value: &T, same: impl Fn(&T, &T) -> bool) -> bool { + let Some(f) = &self.first else { return false }; + if self.all == 0 { + return false; + } + self.all -= 1; + if same(f, value) { + self.same = self.same.saturating_sub(1); + } + if self.same == 0 { + self.first = None; + return self.all == 0; + } + true + } + fn mixed(&self) -> bool { + self.same < self.all + } } impl SelectionPaints { @@ -420,31 +464,76 @@ impl SelectionPaints { p } - /// Read objects `ids` of `doc` too. + /// Do the fills differ? + pub(crate) fn fill_mixed(&self) -> bool { + self.fill.mixed() + } + + /// Do the strokes differ? + pub(crate) fn stroke_mixed(&self) -> bool { + self.stroke.mixed() + } + + /// Do the stroke weights differ? + pub(crate) fn weight_mixed(&self) -> bool { + self.weight.mixed() + } + + /// Is an object a face or edge of a Live Paint group, or inside one? + pub(crate) fn in_live_paint(&self) -> bool { + self.in_live_paint > 0 + } + + /// Is an object a gradient mesh or a container? + pub(crate) fn may_hold_mesh(&self) -> bool { + self.may_hold_mesh > 0 + } + + /// Read objects `ids` of `doc` too: ids that are not read yet, each named once. pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) { - fn meet(first: &mut Option, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) { - match first { - Some(f) => *mixed |= !same(f, &value), - None => *first = Some(value), + self.each(doc, ids, true); + } + + /// Take out objects `ids` of `doc`, read before in the same document: ids that are read, each + /// named once. → false when the objects left must be read again ([`Tally::remove`]); the + /// paints are then wrong. + pub(crate) fn remove(&mut self, doc: &Document, ids: &[NodeId]) -> bool { + self.each(doc, ids, false) + } + + /// [`Self::add`] (`add`) or [`Self::remove`]. + fn each(&mut self, doc: &Document, ids: &[NodeId], add: bool) -> bool { + let mut ok = true; + let mut meet = |tally: &mut Tally, value: Paint| { + if add { + tally.add(value, same_in_proxy); + } else { + ok &= tally.remove(&value, same_in_proxy); } - } - // As in `proxy_mixed_with`: every node with an added id, in tree order. + }; + // As in `proxy_mixed_with`: every node with one of the ids, in tree order. let (mut fills, mut strokes) = (vec![], vec![]); for n in doc.nodes_in_order(ids.iter().copied()) { painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } for n in fills { - meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy); + meet(&mut self.fill, proxy_paint(n, false, None)); } for n in strokes { - meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy); + meet(&mut self.stroke, proxy_paint(n, true, None)); } - // As in `stroke_mixed`: the node each added id names. - for id in ids { + // As in `stroke_mixed`: the node each id names. + let step = |count: &mut usize, yes: bool| { + if yes { + *count = if add { *count + 1 } else { count.saturating_sub(1) }; + } + }; + let mut seen = std::collections::HashSet::new(); + for id in ids.iter().filter(|id| seen.insert(**id)) { let Some(n) = doc.node(*id) else { continue }; - self.in_live_paint |= in_live_paint(doc, *id); - self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container(); + step(&mut self.in_live_paint, in_live_paint(doc, *id)); + step(&mut self.may_hold_mesh, matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); let mut nodes = vec![]; painted(n, true, true, &mut nodes); for n in nodes { @@ -453,10 +542,15 @@ impl SelectionPaints { _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; for w in widths { - meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b); + if add { + self.weight.add(w, |a, b| a == b); + } else { + ok &= self.weight.remove(&w, |a, b| a == b); + } } } } + ok } } @@ -1273,7 +1367,7 @@ impl DocState { /// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group. pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet { - if self.selection_paints().is_some_and(|p| !p.in_live_paint) { + if self.selection_paints().is_some_and(|p| !p.in_live_paint()) { return std::collections::HashSet::new(); } live_paint_covered(&self.doc, ids) @@ -1525,7 +1619,7 @@ impl Session { // Only gradient meshes have points to pick: a selection with no mesh and no container that // could hold one skips reading the tool's options. let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); - let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh); + let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh()); if st.selection.symbol_part.is_some() || none_may() { return vec![]; } diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index 8055a2f326..ec8f02f700 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -266,6 +266,36 @@ fn random_selections_match_a_walk_of_the_document() { } } +/// With an Appearance row active and many objects selected, the opacity proxy (read on every repaint of the Color +/// Wheel panel) and `first_edited` match only the targets they read against the first object's stack, not every +/// target, and still answer with the first object's row. +#[test] +fn an_active_row_matches_only_the_targets_read() { + use super::super::appearance::{ItemTarget, first_edited, stacks_matched}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + let ids: Vec = (0..30).map(|i| rect(&mut s, f64::from(i) * 25.0, "#ff0000", "#0000ff")).collect(); + s.execute("paint.setFill", &json!({"ids": [ids[0].0], "opacity": 40})).unwrap(); + s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + let fill = s.active().unwrap().doc.node(ids[0]).unwrap().appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap(); + assert_eq!(s.appearance_item(), Some(fill)); + + let before = stacks_matched(); + assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the first object's fill opacity"); + assert!(stacks_matched() - before <= 1, "proxy_opacity matched {} stacks for {} targets", stacks_matched() - before, ids.len()); + + let row = ItemTarget::Item { index: fill, explicit: false, aligned: true }; + let before = stacks_matched(); + assert_eq!(first_edited(&s, row, None, &ids), Some((ids[0], row))); + assert!(stacks_matched() - before <= 1, "first_edited matched {} stacks for {} targets", stacks_matched() - before, ids.len()); + + // Reading every target still matches each one but the first. + let before = stacks_matched(); + assert_eq!(row.per_target(&s, &ids).len(), ids.len()); + assert_eq!(stacks_matched() - before, ids.len() as u64 - 1); +} + /// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. fn thread_cpu() -> Option { let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; diff --git a/crates/engine/src/cmd/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/plugin.rs b/crates/engine/src/cmd/plugin.rs index 53d9c3ff29..dcac8cc26e 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1615,8 +1615,14 @@ impl Drop for FolderPending { /// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`: /// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report. -#[cfg(not(target_arch = "wasm32"))] fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + start_folder_files(s, folder, None, record) +} + +/// [`start_folder`] for the one file `only` of `folder` when it is given, without listing the +/// folder ([`registry::FolderLoad::list_file`]). +#[cfg(not(target_arch = "wasm32"))] +fn start_folder_files(s: &Session, folder: &str, only: Option<&std::path::Path>, record: Option) -> FolderPending { let pending = |load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }; if let Err(e) = crate::file_access::check_read(folder) { @@ -1637,11 +1643,15 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending }) }; // The modules start loading once the loads queued before them are done. - pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()}))) + let listed = match only { + Some(file) => registry::FolderLoad::list_file(file, allow), + None => registry::FolderLoad::list(std::path::Path::new(folder), allow), + }; + pending(listed.map_err(|e| json!({"folder": folder, "error": e.to_string()}))) } #[cfg(target_arch = "wasm32")] -fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { +fn start_folder_files(s: &Session, folder: &str, _: Option<&std::path::Path>, record: Option) -> FolderPending { let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"})); FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false } } @@ -1659,6 +1669,13 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S { for id in load.install_ready(s.plugin_folder_approver()) { s.attach_plugin_storage(turn, &id); + // A `plugin.reload` of the plug-in store's own folder installed a stored file that + // failed before. + if let Some(p) = registry::get(&id) + && let Some(source) = p.source() + { + crate::store::clear_stored_failure(std::path::Path::new(source)); + } } // A disabled plug-in's file matched by its id is saved in the same turn. if load.disabled_changed() && s.store_disabled_plugins_in(turn) { @@ -1790,12 +1807,206 @@ fn shown_report(mut report: Value) -> Value { report } -fn list(_: &mut Session, _: &Value) -> Result { +fn list(s: &mut Session, _: &Value) -> Result { let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone())); let disabled: Vec = safe_mode::disabled().iter().map(shown_item).collect(); - Ok( - json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), - ) + let failed: Vec = failed_loads(s).iter().map(shown_failure).collect(); + Ok(json!({ + "plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), + "folder": folder, + "failed": failed, + "safeMode": safe_mode::active(), + "disabled": disabled, + })) +} + +/// Where a plug-in that didn't load was loaded from. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum LoadedFrom { + /// The session's plug-in store. + Store, + /// The Additional Plug-ins Folder, or the folder `plugin.reload` loaded last. + Folder, +} + +impl LoadedFrom { + fn name(self) -> &'static str { + match self { + LoadedFrom::Store => "store", + LoadedFrom::Folder => "folder", + } + } +} + +/// A plug-in file that didn't load in this process: the file, why, and where it was loaded from. +type FailedLoad = (String, String, LoadedFrom); + +/// The plug-in files that didn't load in this process and that a retry may load: those of the +/// session's plug-in store ([`crate::store::failed_stored_plugins`]), then those of the folder last +/// loaded ([`FOLDER`]). A disabled plug-in (it is listed in `disabled`) and one that another install +/// or removal of its id replaced while it loaded are left out. +fn failed_loads(s: &Session) -> Vec { + let mut failed: Vec = s + .plugin_dir + .as_deref() + .map(crate::store::failed_stored_plugins) + .unwrap_or_default() + .into_iter() + .map(|(path, why)| (path.display().to_string(), why, LoadedFrom::Store)) + .collect(); + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref() + && let Some(rows) = report.get("failed").and_then(Value::as_array) + { + for row in rows { + let (Some(file), Some(why)) = (row.get("file").and_then(Value::as_str), row.get("error").and_then(Value::as_str)) else { continue }; + // A `plugin.reload` of the plug-in store's own folder lists its stored files once, as + // stored files. + let stored = failed.iter().any(|(f, _, from)| *from == LoadedFrom::Store && std::path::Path::new(f) == std::path::Path::new(file)); + if why != registry::DISABLED && why != registry::SUPERSEDED && !stored { + failed.push((file.to_string(), why.to_string(), LoadedFrom::Folder)); + } + } + } + // A file turned off since it failed (`plugin.setEnabled`, listed in `disabled`) or skipped in this + // launch, and a stored file whose plug-in id is, are left out. + let off = safe_mode::disabled(); + let stems: std::collections::BTreeSet = + off.iter().filter_map(|i| i.id.clone()).chain(safe_mode::skipped_ids()).map(|id| crate::store::file_stem(&id)).collect(); + failed.retain(|(file, _, from)| { + let item = safe_mode::Item::file(file.clone()); + let by_id = + *from == LoadedFrom::Store && std::path::Path::new(file).file_stem().is_some_and(|s| stems.contains(s.to_string_lossy().as_ref())); + !by_id && !safe_mode::skipped(&item) && !off.iter().any(|i| i.same(&item)) + }); + failed +} + +/// How many plug-in files didn't load in this process and may load on a retry ([`failed_loads`]): +/// Object › Plug-ins › Plug-ins That Didn't Load… is enabled while there is one. +pub fn failed_load_count(s: &Session) -> usize { + failed_loads(s).len() +} + +/// A [`FailedLoad`] as a reply shows it: a file outside the automation read roots by its file name, +/// in its error too. +fn shown_failure((file, why, from): &FailedLoad) -> Value { + json!({"file": shown_file(file), "error": shown_error(file, why), "from": from.name()}) +} + +/// The error `why` about the plug-in file `file` as a reply shows it: the file, and then its folder, +/// outside the automation read roots by their names, as [`shown_report`] shows a folder's errors. +fn shown_error(file: &str, why: &str) -> String { + let folder = std::path::Path::new(file).parent().map(|f| f.display().to_string()).filter(|f| !f.is_empty()); + let why = why.replace(file, &shown_file(file)); + match folder { + Some(folder) => why.replace(folder.as_str(), &shown_file(&folder)), + None => why, + } +} + +/// `plugin.retry`: loads again the plug-in file `file` that didn't load (as `plugin.list`'s `failed` +/// names it), or every one of them without `file`, each as the load it failed in loads it: a stored +/// file as the plug-in store loads its files, and a folder file as `plugin.reload` loads the folder's +/// → `{retried: [{file, loaded, id?, error?}]}`. +fn retry(s: &mut Session, p: &Value) -> Result { + const C: &str = "plugin.retry"; + let failed = failed_loads(s); + let picked: Vec = match p.get("file") { + None => failed, + Some(v) => { + let file = + v.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "`file` must be a file plugin.list's failed names"))?; + // A file outside the automation read roots is named by its file name, when no other + // failed file has it. + let exact: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| f == file).collect(); + let named: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| shown_file(f) == file).collect(); + match (exact.as_slice(), named.as_slice()) { + ([one], _) | ([], [one]) => vec![(*one).clone()], + _ => return Err(bad(C, format!("{file} is not a plug-in that failed to load (see plugin.list's failed)"))), + } + } + }; + safe_mode::check().map_err(err)?; + // Loads started earlier install first, so a retry's module replaces theirs. + s.finish_plugin_loads(); + let mut retried = Vec::with_capacity(picked.len()); + for (file, _, from) in &picked { + let outcome = match from { + LoadedFrom::Store => retry_stored(s, file), + LoadedFrom::Folder => retry_folder_file(s, file), + }; + let shown = shown_file(file); + retried.push(match outcome { + Ok(id) => json!({"file": shown, "loaded": true, "id": id}), + Err(why) => json!({"file": shown, "loaded": false, "error": shown_error(file, &why)}), + }); + } + Ok(json!({ "retried": retried })) +} + +/// Loads the stored plug-in `file` again → the id it installed with, or why it didn't. +fn retry_stored(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + // Under automation read roots, a file outside them is not read again, as a folder file isn't. + crate::file_access::check_read(file)?; + let installed = s.retry_stored_plugin(path); + if let Some(why) = crate::store::stored_failure(path) { + return Err(why); + } + match installed { + Some(id) => { + clear_folder_failure(path); + Ok(id) + } + None if !path.is_file() => Err("the file is no longer in the plug-in store".into()), + // Disabled, or replaced by another install of its id while it loaded. + None => Err("it didn't install".into()), + } +} + +/// Takes `path` out of the folder report's failed files: a stored module may also have failed in +/// a `plugin.reload` of the store's own folder. +pub(crate) fn clear_folder_failure(path: &std::path::Path) { + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && let Some(rows) = report.get_mut("failed").and_then(Value::as_array_mut) + { + rows.retain(|row| row.get("file").and_then(Value::as_str).is_none_or(|f| std::path::Path::new(f) != path)); + } +} + +/// Loads the file `file` of the folder last loaded again, as `plugin.reload` loads each file, and +/// updates that folder's report: the file is listed as loaded or, with the new error, as failed → +/// the id it installed with, or why it didn't. +fn retry_folder_file(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + let folder = path.parent().map(|f| f.display().to_string()).unwrap_or_default(); + let load = start_folder_files(s, &folder, Some(path), None); + let report = s.finish_plugin_load(PluginLoad::Folder(load)); + let loaded: Vec = report.get("loaded").and_then(Value::as_array).cloned().unwrap_or_default(); + let failed: Vec = report.get("failed").and_then(Value::as_array).cloned().unwrap_or_default(); + // A retry that couldn't load the file (its folder can't be read) reports only an error and + // leaves its row as it is. + if report.get("failed").is_some() + && let Some((last, _, r, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && std::path::Path::new(last.as_str()) == std::path::Path::new(&folder) + { + if let Some(rows) = r.get_mut("failed").and_then(Value::as_array_mut) { + rows.retain(|row| row.get("file").and_then(Value::as_str) != Some(file)); + rows.extend(failed.iter().cloned()); + } + if let Some(ids) = r.get_mut("loaded").and_then(Value::as_array_mut) { + for id in &loaded { + if !ids.contains(id) { + ids.push(id.clone()); + } + } + } + } + if let Some(id) = loaded.first().and_then(Value::as_str) { + return Ok(id.to_string()); + } + let why = failed.first().and_then(|row| row.get("error")).and_then(Value::as_str).or_else(|| report.get("error").and_then(Value::as_str)); + Err(why.unwrap_or("it didn't install").to_string()) } /// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch, @@ -1811,15 +2022,16 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result { })) } -/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name +/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source` or in `failed`: one they name /// by its file name (outside the automation read roots) is found by that name, when no other listed /// file has it. -fn listed_file(file: String) -> String { +fn listed_file(s: &Session, file: String) -> String { let mut listed: Vec = safe_mode::disabled() .into_iter() .chain(safe_mode::previous()) .filter_map(|i| i.file) .chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string))) + .chain(failed_loads(s).into_iter().map(|(f, _, _)| f)) .collect(); listed.sort(); listed.dedup(); @@ -1854,7 +2066,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None }; (registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored) } - (None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None), + (None, Some(file)) => (safe_mode::Item::file(listed_file(s, file)), None), (None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")), }; let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect(); @@ -1971,7 +2183,7 @@ fn clear_cache(_: &mut Session, p: &Value) -> Result { } /// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove`, -/// `.reload`, `.clearCache`, `.safeMode` and `.setEnabled`. +/// `.reload`, `.retry`, `.clearCache`, `.safeMode` and `.setEnabled`. pub fn specs() -> Vec { vec![ cmd!( @@ -1979,7 +2191,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -2046,6 +2258,15 @@ pub fn specs() -> Vec { always, reload ), + cmd!( + query "plugin.retry", + "Retry Plug-in", + [], + None, + "{file?: a file plugin.list's failed names (under automation read roots, a file outside them by the file name shown, when no other failed file has it)} load again the plug-in file that didn't load, or every file plugin.list's failed names when file is left out (desktop; a stored file loads as the plug-in store loads its files, and a folder file as plugin.reload loads the folder's, with the same checks; under automation read roots, a file outside them is not read and reports why; a folder file's row in plugin.list's folder report changes to loaded or to its new error; an error in Safe Mode, or when file isn't one that failed) → {retried: [{file, loaded: bool, id? (the plug-in it installed), error? (why it didn't load again)}]}", + always, + retry + ), cmd!( query "plugin.safeMode", "Safe Mode", @@ -2060,7 +2281,7 @@ pub fn specs() -> Vec { "Enable on Re-launch", [], None, - "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", + "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source or failed names it (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", always, set_enabled ), diff --git a/crates/engine/src/cmd/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..f87cc07654 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 @@ -191,6 +194,33 @@ pub(crate) fn objects_only(sel: &Selection) -> bool { && sel.on_path_member.is_none() } +/// How `after` starts with objects of `before` kept in their order: → how many objects of `after` +/// do, and the objects of `before` that are not among them, in order. +pub(crate) fn kept_from(before: &[NodeId], after: &[NodeId]) -> (usize, Vec) { + let (mut at, mut kept, mut removed) = (0, 0, Vec::new()); + for id in after { + let Some(i) = before[at..].iter().position(|b| b == id) else { break }; + removed.extend_from_slice(&before[at..at + i]); + at += i + 1; + kept += 1; + } + removed.extend_from_slice(&before[at..]); + (kept, removed) +} + +/// The objects of `ids` that are not in `of`, each named once, in order. +fn left_out(ids: &[NodeId], of: &[NodeId]) -> Vec { + if ids.is_empty() { + return vec![]; + } + let mut out: std::collections::HashSet = ids.iter().copied().collect(); + for id in of { + out.remove(id); + } + let mut seen = std::collections::HashSet::new(); + ids.iter().copied().filter(|id| out.contains(id) && seen.insert(*id)).collect() +} + /// What the commands scripts ran did to an open document since the person last opened or saved it /// ([`DocState::by_script`]). #[derive(Clone, Debug)] @@ -421,6 +451,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, @@ -467,8 +498,10 @@ impl DocState { self.selection_record().and_then(|r| r.paints.as_ref()) } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with - /// Lock Guides `guides_locked`. `record` is the record of the selection before: when the - /// selected objects start with its objects, the added objects are read into its paints. + /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same + /// document: the objects that leave the selection are taken out of its paints and the objects + /// that join it are read into them, unless that reads more objects than reading the selection + /// again would, or the paints left can't be told apart without reading them again. pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { if !objects_only(&self.selection) { self.selection_record = None; @@ -476,16 +509,22 @@ impl DocState { } let objects = &self.selection.objects; self.selection_record = Some(match record { - Some(mut r) if objects.starts_with(&r.objects) => { - let added = &objects[r.objects.len()..]; + Some(mut r) => { if let Some(p) = &mut r.paints { - p.add(&self.doc, added); + let (kept, removed) = kept_from(&r.objects, objects); + let gone = left_out(&removed, objects); + let joined = left_out(&objects[kept..], &r.objects); + if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) { + r.paints = None; + } else { + p.add(&self.doc, &joined); + } } - r.objects.extend_from_slice(added); + r.objects.clone_from(objects); r.settled = Some(guides_locked); r } - _ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, + None => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, }); } @@ -656,6 +695,32 @@ impl DocState { self.revision += 1; } } + /// End isolation mode when the isolated object is no longer in the document (an edit deleted, + /// cut, ungrouped or replaced it, or Undo or Redo took it out, such as the clip group Draw + /// Inside made around it, #3705), rather than naming an id a later object may take. While + /// opacity mask, pattern or symbol editing is on, isolation goes back to that mode's editing + /// layer. + pub(crate) fn leave_isolation_if_gone(&mut self) { + if self.isolation.is_some_and(|i| self.doc.node(i).is_none()) { + let d = &self.doc; + let layer = d.mask_edit.map(|e| e.layer).or(d.pattern_edit.as_ref().map(|e| e.layer)).or(d.symbol_edit.as_ref().map(|e| e.layer)); + self.isolation = layer.filter(|l| d.node(*l).is_some()); + self.revision += 1; + } + } + /// After the document went back from `undone` to a state from when `before` was isolated (a + /// canceled undo group or undo scope, an interaction's next preview): `before` is isolated + /// again when the edits taken back had removed it. + pub(crate) fn restore_isolation(&mut self, before: Option, undone: &Document) { + if let Some(b) = before + && self.isolation != before + && undone.node(b).is_none() + && self.doc.node(b).is_some() + { + self.isolation = before; + self.revision += 1; + } + } /// Clear the Variables panel highlight when the document defines no variable of that name /// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is /// not highlighted without a click. diff --git a/crates/engine/src/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 46ca2824d4..6a479adc11 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -18,7 +18,8 @@ //! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` //! gives, and a script may name the application's members without `app.`, as //! describes; here -//! that holds for `activeDocument`, `documents` and `selection`. +//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active +//! document, as the same page says. //! //! VectorCraft's own rules: //! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever @@ -29,8 +30,8 @@ //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the //! active document's selection. A top-level `var selection = ...` does the same and does //! not make a variable of the script. Assigning `documents` keeps its value. -//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is -//! always the active document; VectorCraft does not follow that yet. +//! - After `documents[0]`, documents are listed from the one active most recently to the one +//! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the //! group or compound path, and leaves out layers and ruler guides. An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. @@ -651,11 +652,11 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before, layer) = { + let (index, active, before, layer, activated) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let st = &s.documents()[index]; - (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.activated) }; let switch = active != Some(index); if switch { @@ -681,6 +682,13 @@ fn on_doc( Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), _ => Ok(()), }; + // The switch for the change does not move the document up in `documents`. + if switch + && back.is_ok() + && let Some(st) = h.session.borrow_mut().document_mut(uid) + { + st.activated = activated; + } let v = r?; restored?; back?; @@ -840,12 +848,17 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } +/// The open documents in the order `documents` lists them ([`Session::front_order`]). +fn front_docs(s: &Session) -> impl Iterator { + s.front_order().into_iter().map(|i| &s.documents()[i]) +} + /// `documents[i]`, and `documents["name"]` as `getByName` reads it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), - Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)), + Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, }, @@ -857,7 +870,7 @@ fn docs_at(h: &Host, a: &[Data]) -> Answer { fn docs_by_name(h: &Host, a: &[Data]) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + let st = front_docs(&s).find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; Ok(doc_ref(h, st.uid)) } @@ -1180,8 +1193,58 @@ fn preset_of(h: &Host, d: &Data) -> Option { (i < h.dom.presets.borrow().len()).then_some(i) } -/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and -/// a value is checked when `addDocument` uses it. +/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one. +fn preset_enum(key: &str) -> Option<&'static str> { + Some(match key { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => return None, + }) +} + +/// Checks that `value` is of the kind the `DocumentPreset` setting `key` holds: a value of its +/// enumeration, a finite number, a title of at most [`MAX_TEXT_BYTES`] bytes, `true` or `false` for +/// `documentBleedLink`, or four finite numbers for `documentBleedOffsetRect`. `undefined` unsets any +/// setting, and the three settings `addDocument` does not apply yet also take `null`. +fn check_preset_value(key: &str, value: &Data) -> std::result::Result<(), HostError> { + let wrong = |kind: &str| Err(HostError::Type(format!("DocumentPreset.{key} must be {kind}"))); + match value { + Data::Undefined => return Ok(()), + Data::Null if matches!(key, "documentBleedLink" | "documentBleedOffsetRect" | "transparencyGrid") => return Ok(()), + _ => {} + } + if let Some(name) = preset_enum(key) { + let member = ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m); + return match value { + Data::String(s) if s.strip_prefix(name).and_then(|r| r.strip_prefix('.')).is_some_and(|m| member.contains(&m)) => Ok(()), + _ => wrong(&format!("a {name} value")), + }; + } + match key { + "title" => match value { + Data::String(t) if t.len() > MAX_TEXT_BYTES => Err(HostError::Range("the title is too long".into())), + Data::String(_) => Ok(()), + _ => wrong("a string"), + }, + "documentBleedLink" => match value { + Data::Bool(_) => Ok(()), + _ => wrong("true or false"), + }, + "documentBleedOffsetRect" => match value { + Data::Array(r) if r.len() == 4 && r.iter().all(|n| matches!(n, Data::Number(n) if n.is_finite())) => Ok(()), + _ => wrong("an array of four finite numbers"), + }, + _ => number(value, &format!("DocumentPreset.{key}")).map(|_| ()), + } +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`. The +/// setter checks the kind and size of a value ([`check_preset_value`]) and keeps the old value when +/// it throws; `addDocument` checks the ranges. fn preset_field(link: &Link, key: &'static str) -> HostMember { let not_preset = || HostError::Type("this is not a DocumentPreset".into()); let l = link.clone(); @@ -1201,6 +1264,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let value = arg(&a, 1).clone(); h.charge_call(16 + data_size(&value))?; let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + check_preset_value(key, &value)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; match fields.iter_mut().find(|(k, _)| k == key) { 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..3d67b3a482 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -2,7 +2,7 @@ use super::{ Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane, objects_in_range, }; -use crate::doc_state::objects_only; +use crate::doc_state::{kept_from, objects_only}; impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one @@ -149,6 +149,7 @@ impl Session { st.active_layer = st.doc.default_layer(); } } + st.leave_isolation_if_gone(); st.revision += 1; if st.interaction.is_none() { let selection = match st.history.undo.last() { @@ -236,17 +237,19 @@ impl Session { let new_art = st.selection.new_art.clone(); let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; f(&st.doc, &mut st.selection); - let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before); - // Objects added to objects this checked in the same document, with Lock Guides as it was - // then and no art on a locked artboard to protect, are checked alone, by the rules `prune` - // and `deselect_hidden` apply to an object. + // Objects this checked in the same document, kept in their order, with Lock Guides as it + // was then and no art on a locked artboard to protect, need no check again: only the + // objects after them are checked, by the rules `prune` and `deselect_hidden` apply to an + // object. let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked)) + && objects_only(&st.selection) && st.selection.new_art.is_empty() && st.doc.new_art.get().is_empty() && !st.doc.artboards.iter().any(|a| a.locked); - if added && settled { + if settled { let doc = &st.doc; - let tail = st.selection.objects.split_off(before.len()); + let (kept, _) = kept_from(&before, &st.selection.objects); + let tail = st.selection.objects.split_off(kept); st.selection.objects.extend(tail.into_iter().filter(|id| { doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. }))) })); @@ -578,7 +581,8 @@ impl Session { if !Arc::ptr_eq(&st.doc, &it.doc) || selection_changed { st.revision += 1; } - st.doc = it.doc.clone(); + let undone = std::mem::replace(&mut st.doc, it.doc.clone()); + let isolation = it.isolation; // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); @@ -601,6 +605,9 @@ impl Session { // Guides locked and slices locked or hidden during the interaction stay deselected, // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); + // The previous preview's end of isolation mode, when it removed the isolated object, is + // undone with it. + st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); (paint, restore_paint) }; diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 3af4cafe5f..bf7b0bf6f7 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -17,7 +17,8 @@ impl Session { if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); + let isolation = st.isolation; + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint, isolation }); } } @@ -31,7 +32,9 @@ impl Session { let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); + let isolation = st.isolation; + st.undo_group = + Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone(), isolation }); } } } @@ -113,9 +116,10 @@ impl Session { if let Some((before, _)) = e.color_mode_paints { self.paint = before; } - st.doc = e.doc; + let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); + st.restore_isolation(g.isolation, &undone); st.sync_new_art(); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); @@ -229,10 +233,11 @@ impl Session { .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); + let isolation = st.isolation; if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) + Some(UndoScope { uid, journal, joined, isolation, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -268,8 +273,9 @@ impl Session { } Some(_) => return, } - st.doc = doc; + let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 29cd6f1bea..1437e9c56c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -180,26 +180,28 @@ fn list_files(dir: &Path, ext: &str) -> Vec { /// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it. fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> { let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; - let mut files: Vec<_> = entries - .filter_map(Result::ok) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext))) - .filter_map(|p| { - let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; - match m.modified() { - Ok(t) => Some((p, (m.len(), t))), - Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", p.display()); - None - } - } - }) - .collect(); + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).filter_map(|p| stamped_file(p, ext)).collect(); files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase())); files.truncate(MAX_STORE_FILES); files } +/// The file `p` with its size and modified time, as [`list_stamped_files`] lists it: `None` unless +/// it is a regular file with the extension `ext`. +fn stamped_file(p: PathBuf, ext: &str) -> Option<(PathBuf, (u64, SystemTime))> { + if !p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)) { + return None; + } + let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; + match m.modified() { + Ok(t) => Some((p, (m.len(), t))), + Err(e) => { + skip_stored(&p, e); + None + } + } +} + /// The content of `path` when it is at most `max` bytes; the file is never read past `max`. pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; @@ -312,6 +314,8 @@ pub(crate) struct StoredLoad { loads: Loads, /// Outcomes taken from `loads` and not installed yet, in order. loaded: VecDeque>, + /// The ids this load installed, in file-name order. + installed: Vec, /// The next file to install. next: usize, /// The store's grants this load removed, by id, because the module stored for the id lists no @@ -369,6 +373,45 @@ fn after_stored_load(path: &Path) { /// Why a stored plug-in whose file changed between its listing and its install is skipped. const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded"; +/// The stored plug-in files that didn't install in this process, by path, with why +/// ([`skip_stored`]). A file stays listed until it installs or its store is loaded again. +static STORED_FAILED: Mutex> = Mutex::new(BTreeMap::new()); + +/// The stored plug-ins skipped ([`STORED_FAILED`]). +fn stored_failures() -> MutexGuard<'static, BTreeMap> { + STORED_FAILED.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Skips the stored plug-in `path` because of `why`: logs it and lists the file as failed. +fn skip_stored(path: &Path, why: impl std::fmt::Display) { + log::warn!("skipping the stored plug-in {}: {why}", path.display()); + stored_failures().insert(path.to_path_buf(), why.to_string()); +} + +/// The stored plug-in files in the plug-in store `dir` that didn't install in this process, in +/// file-name order, each with why. +pub(crate) fn failed_stored_plugins(dir: &Path) -> Vec<(PathBuf, String)> { + stored_failures().iter().filter(|(p, _)| p.parent() == Some(dir)).map(|(p, why)| (p.clone(), why.clone())).collect() +} + +/// Stops listing the stored plug-in file `path` as failed: a plug-in installed from it. +pub(crate) fn clear_stored_failure(path: &Path) { + stored_failures().remove(path); +} + +/// A plug-in installed from the stored file `path`: it is no longer listed as failed, by the store +/// (a load in another session may have failed on it meanwhile) or by the folder report of a +/// `plugin.reload` of the store's folder. +fn installed_from(path: &Path) { + clear_stored_failure(path); + crate::cmd::plugin::clear_folder_failure(path); +} + +/// Why the stored plug-in `path` didn't install in this process, if it is listed as failed. +pub(crate) fn stored_failure(path: &Path) -> Option { + stored_failures().get(path).cloned() +} + #[cfg(test)] thread_local! { /// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]). @@ -408,11 +451,15 @@ fn list_stored_plugins(rest: &mut VecDeque, left: &mut u64) -> (Vec< let most = *left + taken; if most == 0 { log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); - rest.clear(); + let why = format!("the stored plug-ins hold more than {MAX_PLUGIN_STORE} bytes together"); + let mut failed = stored_failures(); + for (path, _) in std::iter::once((path, stamp)).chain(rest.drain(..)) { + failed.insert(path, why.clone()); + } break; } if len > most { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most)); + skip_stored(&path, too_large(most)); continue; } // An empty file too waits once `left` is used up. @@ -491,15 +538,40 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } -/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while +/// A lock file this process locked, unlocked when it is dropped. A child process that any thread +/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed +/// by closing every copy or by unlocking. +pub(crate) struct LockedFile(std::fs::File); + +impl LockedFile { + /// `file`, which the caller has locked. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new(file: std::fs::File) -> Self { + LockedFile(file) + } + + /// The locked file. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn file(&self) -> &std::fs::File { + &self.0 + } +} + +impl Drop for LockedFile { + fn drop(&mut self) { + let _ = self.0.unlock(); + } +} + +/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until it is dropped, waiting while /// another window or process holds it, or another handle in this process. The file is opened for /// reading and writing (a handle that only appends can't be locked on Windows) and is never /// replaced or removed, so that every window locks the same file. #[cfg(not(target_arch = "wasm32"))] -fn lock_store(dir: &Path) -> std::io::Result { +fn lock_store(dir: &Path) -> std::io::Result { let file = open_store_lock(dir)?; match file.try_lock() { - Ok(()) => return Ok(file), + Ok(()) => return Ok(LockedFile::new(file)), Err(std::fs::TryLockError::WouldBlock) => {} Err(std::fs::TryLockError::Error(e)) => return Err(e), } @@ -508,7 +580,7 @@ fn lock_store(dir: &Path) -> std::io::Result { waiting(); } file.lock()?; - Ok(file) + Ok(LockedFile::new(file)) } /// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked. @@ -520,10 +592,10 @@ fn open_store_lock(dir: &Path) -> std::io::Result { /// [`lock_store`] without waiting: `None` while another window or process holds the lock. #[cfg(not(target_arch = "wasm32"))] -fn try_lock_store(dir: &Path) -> std::io::Result> { +fn try_lock_store(dir: &Path) -> std::io::Result> { let file = open_store_lock(dir)?; match file.try_lock() { - Ok(()) => Ok(Some(file)), + Ok(()) => Ok(Some(LockedFile::new(file))), Err(std::fs::TryLockError::WouldBlock) => Ok(None), Err(std::fs::TryLockError::Error(e)) => Err(e), } @@ -531,13 +603,13 @@ fn try_lock_store(dir: &Path) -> std::io::Result> { /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn try_lock_store(_: &Path) -> std::io::Result> { +fn try_lock_store(_: &Path) -> std::io::Result> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn lock_store(_: &Path) -> std::io::Result { +fn lock_store(_: &Path) -> std::io::Result { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } @@ -548,7 +620,7 @@ fn lock_store(_: &Path) -> std::io::Result { pub(crate) struct StoreTurn { /// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without /// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store. - lock: Option, + lock: Option, } impl StoreTurn { @@ -557,6 +629,12 @@ impl StoreTurn { StoreTurn { lock: None } } + /// Tests: the locked [`DISABLED_LOCK`], when the turn is held. + #[cfg(test)] + pub(crate) fn lock_file(&self) -> Option<&std::fs::File> { + self.lock.as_ref().map(LockedFile::file) + } + /// Whether the store may be written in this turn. fn held(&self) -> bool { self.lock.is_some() @@ -743,7 +821,7 @@ impl Session { pub fn attach_plugin_store(&mut self, dir: PathBuf) { self.finish_plugin_loads(); self.plugin_dir = Some(dir); - self.start_stored_plugins(true); + self.start_stored_plugins(true, None); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user @@ -760,34 +838,58 @@ impl Session { /// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With /// [`Session::load_plugins_in_background`] on, this returns while the modules load. pub fn load_stored_plugins(&mut self) { - self.start_stored_plugins(false); + self.start_stored_plugins(false, None); + } + + /// Loads the stored plug-in `path` again, as [`Session::load_stored_plugins`] loads each file, + /// and waits until it is installed or skipped (`plugin.retry`) → the id it installed, if any. + pub(crate) fn retry_stored_plugin(&mut self, path: &Path) -> Option { + self.finish_plugin_loads(); + self.start_stored_plugins(false, Some(path)) } /// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the - /// folder ([`DISABLED_FILE`]). - fn start_stored_plugins(&mut self, disabled: bool) { - let Some(dir) = self.plugin_dir.clone() else { return }; + /// folder ([`DISABLED_FILE`]); `only`: load that one file of the folder, if it is there. The + /// files it loads stop being listed as failed ([`failed_stored_plugins`]) until they fail again. + /// With `only`, waits for the load → the id it installed, if any. + fn start_stored_plugins(&mut self, disabled: bool, only: Option<&Path>) -> Option { + let dir = self.plugin_dir.clone()?; // A `plugin.install` in another session or process writes the store before this lists it. let held = crate::cmd::plugin::hold_plugin_changes(); let turn = self.plugin_store_turn_for_load(); + match only { + Some(path) => { + stored_failures().remove(path); + } + None => stored_failures().retain(|p, _| p.parent() != Some(dir.as_path())), + } if disabled { let path = dir.join(DISABLED_FILE); let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(saved); } if safe_mode::active() { - return; + return None; } let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64; let mut rest = VecDeque::new(); let disabled: BTreeSet = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect(); - for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) { + // A retry reads its one file without listing the folder again. + let listed: Vec<_> = match only { + Some(path) => stamped_file(path.to_path_buf(), PLUGIN_EXT).filter(|(p, _)| p.parent() == Some(dir.as_path())).into_iter().collect(), + None => list_stamped_files(&dir, PLUGIN_EXT), + }; + // A retried file that isn't there (yet) stays listed, so a later retry can load it. + if let Some(path) = only.filter(|p| listed.is_empty() && stored_failure(p).is_none()) { + skip_stored(path, "it is no longer in the plug-in store"); + } + for (path, stamp) in listed { let item = safe_mode::Item::file(path.display().to_string()); let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref())); if safe_mode::skipped(&item) || by_id { log::info!("skipping the stored plug-in {}: disabled", path.display()); } else if stamp.0 > module { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module)); + skip_stored(&path, too_large(module)); } else { rest.push_back((path, Some(Some(stamp)))); } @@ -799,9 +901,24 @@ impl Session { changes.start(); // The modules load after the turn, once the loads queued before them are done. drop((turn, held)); - let load = - StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left }; + let load = StoredLoad { + dir, + files, + loads: Loads::deferred(jobs), + loaded: VecDeque::new(), + installed: Vec::new(), + next: 0, + retired: BTreeMap::new(), + changes, + rest, + left, + }; + if only.is_some() { + let report = self.finish_plugin_load(PluginLoad::Stored(load)); + return report["loaded"].as_array()?.first()?.as_str().map(str::to_string); + } self.queue_plugin_load(PluginLoad::Stored(load)); + None } /// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the @@ -846,7 +963,7 @@ impl Session { // The worker read the file again once its module loaded ([`list_stored_plugins`]); one // whose stamp changed since then is skipped too. if file_stamp(path).ok() != *stamp { - log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display()); + skip_stored(path, CHANGED_WHILE_LOADING); continue; } match loaded { @@ -870,7 +987,7 @@ impl Session { // grant it, so it wouldn't load at the next launch either. if back.is_some() { if !self.store_grant_in(turn, &m.id, Some(g.clone())) { - log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display()); + skip_stored(path, "couldn't put back its grant"); continue; } load.retired.remove(&m.id); @@ -891,6 +1008,8 @@ impl Session { ) { Ok(Some(p)) => { load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); true } Ok(None) => { @@ -898,7 +1017,7 @@ impl Session { false } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); false } }; @@ -914,9 +1033,7 @@ impl Session { } } } - None => { - log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display()) - } + None => skip_stored(path, "the user hasn't granted this module the permissions it lists"), } } Ok(plugin) => { @@ -937,11 +1054,13 @@ impl Session { continue; } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); continue; } }; load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); // In the same turn: the grants for the id stop counting, the process's and the // store's, so no session sees the earlier module as approved. A module installed // in its place meanwhile keeps the process's grant recorded for it. @@ -958,7 +1077,7 @@ impl Session { } } } - Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), + Err(e) => skip_stored(path, e), } } } @@ -1042,7 +1161,7 @@ impl Session { } /// Waits for `load`'s modules and installs them as they load, in turns on the store, then - /// ends it → its report (a folder's; `null` for the stored plug-ins). + /// ends it → its report (the installed ids for the stored plug-ins). pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value { load.start(); loop { @@ -1111,7 +1230,7 @@ impl Session { } } - /// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's). + /// Ends `load` once [`PluginLoad::done`], in `turn` → its report. fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value { // The loads queued after it count what it installed as their own: one of theirs replaces // it, as it would have with the loads run one after the other. @@ -1124,7 +1243,7 @@ impl Session { } match load { // A stored load's grants were settled as each module installed. - PluginLoad::Stored(_) => Value::Null, + PluginLoad::Stored(load) => serde_json::json!({"loaded": load.installed}), PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn), } } @@ -1257,9 +1376,19 @@ impl Session { } /// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there - /// (`false` without a folder, and when `turn` isn't held). + /// (`false` without a folder, and when `turn` isn't held). The file written is no longer listed + /// as failed ([`failed_stored_plugins`]). pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes)) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let written = put(dir, &name, bytes); + if written { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + written + }) } /// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and @@ -1465,9 +1594,19 @@ impl Session { } /// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a - /// folder, and when `turn` isn't held). + /// folder, and when `turn` isn't held). A file removed is no longer listed as failed + /// ([`failed_stored_plugins`]). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let gone = take(dir, &name); + if gone { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + gone + }) } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without @@ -1838,7 +1977,7 @@ impl PluginStorage { /// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a /// window or process changing the same settings or cache waits for this change. - fn turn(&self) -> Result { + fn turn(&self) -> Result { lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}"))) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 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/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 81d6b3bc65..b3ca69fbc7 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -721,3 +721,30 @@ fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() { assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); } + +/// `select.toggle` run once for each of `n` selected objects, in the order they were selected, +/// until none is selected → the walks of the tree and the lookups by id it took. +fn remove_one_at_a_time(n: usize) -> (u64, u64) { + let mut s = session(n, square); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + for id in &ids { + s.execute("select.toggle", &json!({"id": id.0})).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty()); + (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups) +} + +/// Deselecting objects one at a time checks and reads only the object each `select.toggle` takes +/// out: twice as many objects take about twice as many lookups, and the tree is not walked for +/// each one. +#[test] +fn deselecting_objects_one_at_a_time_looks_up_only_the_removed_objects() { + let (walks, lookups) = remove_one_at_a_time(1_000); + let (more_walks, more_lookups) = remove_one_at_a_time(2_000); + assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); + assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 6f7fe9c581..b4aad6c7e6 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1153,6 +1153,28 @@ fn transform_each_random_is_deterministic_with_seed() { assert!(x.x0.abs() <= 50.0 && x.width() == 100.0); } +/// Random with the same horizontal and vertical scale scales each object evenly, Relative and +/// Absolute alike: one random share takes both sides toward the value, so squares stay square, each +/// by its own share (#9320). +#[test] +fn transform_each_random_with_equal_scales_keeps_proportions() { + for p in [ + json!({"scaleH": 40, "scaleV": 40, "random": true, "seed": 7}), + json!({"scaleH": 40, "scaleV": 40, "relative": false, "random": true, "seed": 7}), + ] { + let mut s = session(); + let ids: Vec = (0..8).map(|i| rect(&mut s, f64::from(i) * 150.0, 0.0, 100.0, 100.0)).collect(); + sel(&mut s, &ids); + s.execute("object.transformEach", &p).unwrap(); + let sizes: Vec<(f64, f64)> = ids.iter().map(|id| bounds(&s, *id)).map(|b| (b.width(), b.height())).collect(); + for (w, h) in &sizes { + assert!(close(*w, *h), "{p}: a square came out {w} × {h}"); + assert!(*w < 100.0, "{p}: a square didn't shrink: {w}"); + } + assert!(sizes.iter().any(|(w, _)| !close(*w, sizes[0].0)), "{p}: every square took the same share: {sizes:?}"); + } +} + /// A `reference` or `seed` that is not a whole number (a fraction, a negative number or a string) is an error naming /// the key, and the object stays as it was; a `reference` of 0.0 is the top-left point. #[test] diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index b139ee5927..0c6cc8dfdc 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -233,6 +233,43 @@ fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() { assert_eq!(s.paint.fill, blue, "a, b and c are all blue now"); } +fn toggle(s: &mut Session, id: NodeId) { + run(s, "select.toggle", json!({"id": id.0})); +} + +/// Objects taken out one at a time leave the others to be compared: a fill and weight the objects +/// left share loads, one they don't stays as it was. +#[test] +fn objects_taken_out_one_at_a_time_load_only_the_paints_the_objects_left_share() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#00ffff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0); + let d = painted(&mut s, 320.0, "#ff0000", "#00ff00", 5.0); + let red = node(&s, a).appearance.fill_paint(); + select(&mut s, &[a, b, c, d]); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + toggle(&mut s, c); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 5.0), "a, b and d share the weight, not the fill"); + s.paint.stroke_width = 0.5; + toggle(&mut s, b); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and d share both"); +} + +/// Taking out every object with the fill met first leaves the other objects' fills to compare. +#[test] +fn taking_out_the_objects_with_the_first_fill_compares_the_fills_left() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#0000ff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0); + let blue = node(&s, b).appearance.fill_paint(); + select(&mut s, &[a, b, c]); + s.paint.fill = Paint::None; + toggle(&mut s, a); + assert_eq!(s.paint.fill, blue, "b and c are both blue"); +} + #[test] fn art_without_paint_leaves_the_proxies_as_they_were() { let mut s = session(); diff --git a/crates/engine/src/tests/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/place.rs b/crates/engine/src/tests/place.rs index 7086c7f92e..94da32aa01 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -1224,9 +1224,16 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to let reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view).unwrap(); let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") }; assert_eq!(p["rect"], json!([10.0, 10.0, 40.0, 20.0])); + assert_eq!(p[vectorcraft_tools::place::SOURCE_INDEX], 0); + assert_eq!(p[vectorcraft_tools::place::CLICK], true); assert!(top_children(&s).is_empty(), "the frontend places it"); assert_eq!(s.tool_options()["names"], json!(["b.png"]), "the cursor goes on to the next file"); - s.execute("file.place", p).unwrap(); + // The frontend consumes the private source identity before placing the file. + let mut p = p.clone(); + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + p.as_object_mut().unwrap().remove(key); + } + s.execute("file.place", &p).unwrap(); // Left out: the second each document was made in. let doc = |s: &Session| { let mut d = (*s.doc().unwrap().doc).clone(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index e1b4f6aad0..3458c5ae37 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -181,6 +181,33 @@ fn a_placed_document_is_vectors_in_every_output() { assert!(info.to_string().contains("\"placedDocuments\""), "{info}"); } +#[test] +fn a_placed_documents_spot_color_stays_a_spot_color_in_a_cmx_file() { + let dir = Folder::new("placed-cmx-spot"); + let src = dir.file("logo.vectorcraft"); + let mut d = Document::new(100.0, 50.0); + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + d.swatches.push(vectorcraft_color::Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true }); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let paint = Paint::Solid { color: gold, swatch: Some("Gold".into()), tint: 1.0 }; + let look = Appearance::basic(paint, Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + place(&mut s, &src); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none(), "the placing document has no swatch of that name"); + let bytes = decode(&s.execute("document.serialize", &json!({"format": "cmx"})).unwrap()); + let drawing = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap(); + let mut fills = Vec::new(); + for o in drawing.pages.iter().flat_map(|p| &p.layers).flat_map(|l| &l.objects) { + if let craft_cdr::model::Object::Shape(shape) = o { + fills.extend(shape.fill.clone()); + } + } + assert!(fills.iter().any(|c| matches!(c, craft_cdr::model::Color::Spot { name, .. } if name == "Gold")), "{fills:?}"); +} + #[test] fn the_preview_is_saved_so_the_document_shows_it_without_its_file() { let dir = Folder::new("placed-saved"); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index e47eb8377a..ab4681e68d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -16,7 +16,7 @@ const DESATURATE_ID: &str = "org.vectorcraft.example.desaturate"; /// Held by the tests that set the Additional Plug-ins Folder preference or run `plugin.reload`: /// the folder last loaded and its report are kept for the whole process, so another test loading /// its own folder between two steps would change what the next step loads or lists. -static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); +pub(super) static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) @@ -2350,6 +2350,271 @@ fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::P (folder, path) } +/// The rows of `plugin.list`'s `failed` as (file, from). +fn failed_rows(s: &mut Session) -> Vec<(String, String)> { + let list = run(s, "plugin.list", json!({})); + list["failed"].as_array().unwrap().iter().map(|r| (r["file"].as_str().unwrap().to_string(), r["from"].as_str().unwrap().to_string())).collect() +} + +/// A stored module whose load panics is listed as failed while the store's other plug-in installs, +/// and `plugin.retry` installs it once its load no longer panics. +#[test] +fn a_stored_plugin_whose_load_panicked_is_listed_and_loads_on_retry() { + let (folder, broken) = store_with("plugin-store-retry", "test.engine.retrypanics"); + let good = folder.0.join("test.engine.retryloads.wasm"); + std::fs::write(&good, wat::parse_str(tpl::returning(&tpl::manifest("test.engine.retryloads", "filter", "{}"), r#"{"objects":[]}"#)).unwrap()) + .unwrap(); + let file = broken.display().to_string(); + let mut s = session(); + { + let _lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let target = broken.clone(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| { + if p == target { + panic!("a load that panics"); + } + })); + s.attach_plugin_store(folder.0.clone()); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + assert!(vectorcraft_plugins::registry::get("test.engine.retryloads").is_some(), "the other stored plug-in installs"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none()); + let list = run(&mut s, "plugin.list", json!({})); + let row = list["failed"].as_array().unwrap().iter().find(|r| r["file"] == json!(file)).cloned(); + assert!(row.as_ref().is_some_and(|r| r["from"] == "store" && r["error"].as_str().unwrap().contains("panicked")), "{list}"); + + // Under read roots that leave the store out, the client names it by its file name and its file + // isn't read again. + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = "test.engine.retrypanics.wasm"; + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": name}))).unwrap(); + assert_eq!((&r["retried"][0]["file"], &r["retried"][0]["loaded"]), (&json!(name), &json!(false)), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none(), "not loaded outside the roots"); + + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": "test.engine.retrypanics"}]), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_some(), "installed on retry"); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "no longer listed as failed"); + assert!(s.execute("plugin.retry", &json!({"file": file})).is_err(), "a file that didn't fail is refused"); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrypanics"})); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retryloads"})); +} + +/// A folder file that didn't load stays listed as failed until a retry loads it, which also moves +/// it to the folder report's loaded ids; `plugin.reload` replaces the folder's failed files with its +/// own and leaves the plug-in store's alone. +#[test] +fn a_folder_plugin_loads_on_retry_and_reload_replaces_only_the_folder_s_failures() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // The file the store keeps the module of plug-in `test.engine.retrystored` in, which isn't a module. + let store = crate::tests_links::Folder::new("plugin-store-retry-reload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retrystored"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let dir = crate::tests_links::Folder::new("plugin-folder-retry"); + let id = "test.engine.retryfolder"; + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + let broken = dir.0.join("later.wasm"); + std::fs::write(&broken, b"\0asm?").unwrap(); + let (file, stored_file) = (broken.display().to_string(), stored.display().to_string()); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let path = dir.0.display().to_string(); + run(&mut s, "plugin.reload", json!({"path": path})); + let both = failed_rows(&mut s); + assert!(both.contains(&(stored_file.clone(), "store".into())) && both.contains(&(file.clone(), "folder".into())), "{both:?}"); + + // Under read roots that leave the folder out, it isn't read and stays listed. + let elsewhere = crate::tests_links::Folder::new("plugin-folder-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": "later.wasm"}))).unwrap(); + assert_eq!(r["retried"][0]["loaded"], json!(false), "{r}"); + let why = r["retried"][0]["error"].as_str().unwrap(); + assert!(!why.is_empty() && !why.contains(path.as_str()), "the folder outside the roots isn't named: {r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into())), "still listed after a retry that couldn't read it"); + + // Still broken: it is listed with the new error. + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!((r["retried"][0]["loaded"].clone(), r["retried"].as_array().unwrap().len()), (json!(false), 1), "{r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into()))); + + std::fs::write(&broken, &module).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": id}]), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert_eq!(list["folder"]["loaded"], json!([id]), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + assert_eq!(failed_rows(&mut s), vec![(stored_file.clone(), "store".into())]); + + // A reload that finds it broken again lists it again, and the stored file stays listed. + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&broken, b"\0asm?").unwrap(); + run(&mut s, "plugin.reload", json!({"path": path})); + let again = failed_rows(&mut s); + assert!(again.contains(&(stored_file.clone(), "store".into())) && again.contains(&(file, "folder".into())), "{again:?}"); + + // Removing the stored module that didn't load takes it off the list. + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrystored"})); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == stored_file), "a removed file is no longer listed"); +} + +/// A stored file that also fails in a `plugin.reload` of the store's own folder is listed once, and a +/// retry by its name installs it and takes it out of the folder report's failed files too. +#[test] +fn a_reload_of_the_store_folder_lists_a_failed_stored_file_once() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryboth"; + let store = crate::tests_links::Folder::new("plugin-store-retry-both"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + let rows = failed_rows(&mut s); + assert_eq!(rows.iter().filter(|(f, _)| std::path::Path::new(f) == stored).count(), 1, "{rows:?}"); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"][0]["loaded"], json!(true), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Removing or replacing a stored module also clears a failure recorded by a reload of the store +/// folder, without clearing another file's failure. +#[test] +fn removing_or_replacing_a_stored_plugin_clears_its_folder_failure() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreplaced"; + let store = crate::tests_links::Folder::new("plugin-store-retry-replaced"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let other = store.0.join("other.wasm"); + std::fs::write(&other, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + for replace in [false, true] { + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + if replace { + install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + } else { + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!stored.exists(), "the broken module was removed"); + } + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|row| row["file"] == file), "{list}"); + let rows = list["folder"]["failed"].as_array().unwrap(); + assert!(!rows.iter().any(|row| row["file"] == file), "{list}"); + assert!(rows.iter().any(|row| row["file"] == other.display().to_string()), "the other failure stays: {list}"); + let retry = run(&mut s, "plugin.retry", json!({})); + assert!(!retry["retried"].as_array().unwrap().iter().any(|row| row["file"] == file), "{retry}"); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// An older installed module doesn't make a retry succeed when the failed stored file is gone. +#[test] +fn retrying_a_missing_stored_plugin_does_not_count_its_old_installation() { + let id = "test.engine.retrymissing"; + let (store, stored) = store_with("plugin-store-retry-missing", id); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).unwrap(); + assert_eq!(installed.source(), Some(file.as_str())); + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + std::fs::remove_file(&stored).unwrap(); + // A retry still waits for its own load when startup loads run in the background. + s.load_plugins_in_background(true); + let retry = run(&mut s, "plugin.retry", json!({"file": file})); + let row = &retry["retried"][0]; + assert_eq!(row["loaded"], json!(false), "{retry}"); + assert!(row.get("id").is_none() && row["error"].as_str().is_some_and(|e| !e.is_empty()), "{retry}"); + assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().serial(), installed.serial(), "the old installation stays"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "still listed, so a later retry can load it"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that also failed in a `plugin.reload` of the store's folder is taken out of the +/// folder report once a store load installs it, here another session attaching the store. +#[test] +fn a_store_load_that_installs_a_failed_file_clears_its_folder_row() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retrystoreload"; + let store = crate::tests_links::Folder::new("plugin-store-retry-storeload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let mut other = session(); + other.attach_plugin_store(store.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the other session's store load installed it"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["folder"]["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that failed and is then repaired is no longer listed once a `plugin.reload` of the +/// store's own folder installs it. +#[test] +fn a_reload_that_installs_a_failed_stored_file_takes_it_off_the_list() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreloaded"; + let store = crate::tests_links::Folder::new("plugin-store-retry-reloaded"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the reload installed it"); + let rows = failed_rows(&mut s); + assert!(!rows.iter().any(|(f, _)| std::path::Path::new(f) == stored), "{rows:?}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A file turned off after it failed to load is no longer listed as failed, also when it is turned +/// off by the name `failed` gives a file outside the read roots; turned on again, it is listed. +#[test] +fn a_failed_file_turned_off_is_no_longer_listed() { + // Another test's store load replaces the process's list of disabled plug-ins. + if !in_own_process("a_failed_file_turned_off_is_no_longer_listed") { + return; + } + let store = crate::tests_links::Folder::new("plugin-store-retry-off"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retryoff"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-off-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = stored.file_name().unwrap().to_string_lossy().to_string(); + crate::file_access::confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": name, "enabled": false}))).unwrap(); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "a file turned off isn't listed"); + assert!(run(&mut s, "plugin.retry", json!({}))["retried"].as_array().unwrap().is_empty()); + + run(&mut s, "plugin.setEnabled", json!({"file": file, "enabled": true})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "listed again once on"); +} + /// With loads in the background, attaching a plug-in store returns while a stored module is /// still loading: the plug-in installs once its load is done, at the next plug-in command. #[test] @@ -4256,6 +4521,21 @@ fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant() run(&mut s, "plugin.remove", json!({"id": id})); } +/// A turn on a plug-in store that ends frees the store while a copy of the lock file's handle is +/// open, as a child process that is starting holds one: another process can take a turn. +#[test] +fn an_ended_store_turn_frees_the_store_while_a_copy_of_its_handle_is_open() { + let folder = crate::tests_links::Folder::new("plugin-store-turn-copied"); + let s = other_process(folder.0.clone()); + let turn = s.plugin_store_turn().unwrap(); + let copy = turn.lock_file().map(|file| file.try_clone().unwrap()); + assert!(copy.is_some(), "the turn is held"); + drop(turn); + let other = std::fs::File::options().read(true).write(true).open(folder.0.join(crate::store::DISABLED_LOCK)).unwrap(); + assert!(other.try_lock().is_ok(), "an ended turn frees the store"); + drop(copy); +} + /// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the /// second write reads `grants.json` only once the first has written it. #[test] diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 7a339b6cbd..e2e2d3dae7 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -641,10 +641,11 @@ fn selection_preferences_drive_the_selection_tool() { assert!(click(&mut s, 225.0, plain).is_empty(), "a click inside the fill selects nothing"); assert_eq!(click(&mut s, 250.0, plain), vec![front], "a click on the path selects it"); set(&mut s, "objectSelectionByPathOnly", json!(false)); - // Command Click to Select Objects Behind (on by default): each Cmd/Ctrl-click goes one down, - // then back to the top. + // Command Click to Select Objects Behind (on by default): the first Cmd/Ctrl-click is Direct + // Selection's, then each one goes one down, then back to the top. let cmd = Mods { cmd: true, ..Mods::default() }; assert_eq!(click(&mut s, 175.0, plain), vec![front]); + assert_eq!(click(&mut s, 175.0, cmd), vec![front], "the first Cmd-click arms Select Behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![back], "the object behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![front], "back to the topmost"); set(&mut s, "ctrlClickSelectsBehind", json!(false)); diff --git a/crates/engine/src/tests/prefs_roots.rs b/crates/engine/src/tests/prefs_roots.rs index b9818949f1..379ce9dca0 100644 --- a/crates/engine/src/tests/prefs_roots.rs +++ b/crates/engine/src/tests/prefs_roots.rs @@ -55,6 +55,8 @@ fn holds(v: &Value, path: &str) -> bool { #[test] fn prefs_commands_leave_out_folders_outside_the_read_root() { + // `prefs.set` and `prefs.reset` load the Additional Plug-ins Folder this session names. + let _folder = super::plugins::PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let base = folder("get"); let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out"))); let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index dfcb58524f..ec805060e9 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -789,6 +789,23 @@ fn an_area_tidied_away_before_it_is_locked_is_busy() { let _ = std::fs::remove_dir_all(&base); } +/// A dropped hold frees its area while a copy of the lock file's handle is open, as a child +/// process that is starting holds one: the area can be locked again. +#[test] +fn a_dropped_hold_frees_the_area_while_a_copy_of_its_handle_is_open() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-copied-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + let Ok(Lock::Held(hold)) = store.lock("6-1") else { panic!("the area is locked") }; + let copy = hold.downcast_ref::().map(|locked| locked.file().try_clone().unwrap()); + assert!(copy.is_some(), "the hold is the locked file"); + drop(hold); + assert!(matches!(store.lock("6-1"), Ok(Lock::Held(_))), "a dropped hold frees the area"); + drop(copy); + let _ = std::fs::remove_dir_all(&base); +} + /// Opening an area's lock file failed. When the folder went after it was checked, or the lock file /// is there but can't be opened (a removed lock file that another app still has open, on file /// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1aa77e6a6..5a0c2a94cf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -46,7 +46,7 @@ fn app_documents_track_active_tab_and_new_document() { let out = log( &mut s, "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ - app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + app.activeDocument = d[1]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ @@ -297,7 +297,7 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert_eq!(s.active().unwrap().selection.objects, vec![a]); // An item of another document cannot be selected here. s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];"); assert!(e.contains("Cannot select"), "{e}"); } @@ -324,13 +324,44 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() { fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); + log(&mut s, "var d = app.documents[1]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); assert_eq!(s.active_index(), Some(1)); let first = &s.documents()[0]; assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); assert_eq!(first.selection.objects.len(), 1); } +#[test] +fn documents_list_the_current_document_first_then_the_most_recently_current() { + let mut s = Session::new(); + for _ in 0..3 { + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + } + let out = log( + &mut s, + "var t = {}, n = ['A', 'B', 'C'];\ + for (var i = 0; i < 3; i++) t[app.documents[2 - i].name] = n[i];\ + function order() { var r = []; for (var i = 0; i < app.documents.length; i++) r.push(t[app.documents[i].name]); return r.join(''); }\ + var A = app.documents[2], B = app.documents[1], C = app.documents[0];\ + vc.log(order());\ + app.activeDocument = A; vc.log(order());\ + app.activeDocument = B; vc.log(order());\ + app.activeDocument = app.documents[2]; vc.log(order());\ + A.pageItems[0].name = 'far'; vc.log(order());\ + vc.log([app.documents[0] === app.activeDocument, app.documents.getByName(B.name) === B]);", + ); + // A change to a document in the back leaves the order as it was. + assert_eq!(out, vec![json!("CBA"), json!("ACB"), json!("BAC"), json!("CBA"), json!("CBA"), json!([true, true])]); + // Closing a document in the back keeps the others in their order as the tabs shift. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 2})).unwrap(); + assert_eq!(s.front_order(), vec![2, 1, 0]); + s.close_document(0); + assert_eq!(s.front_order(), vec![1, 0]); +} + #[test] fn move_duplicate_and_zorder_obey_parent_order() { let (mut s, a, b) = doc(); @@ -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..bc9e2aa0c6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -27,6 +27,8 @@ pub(crate) struct HoverKey { use_preview_bounds: bool, type_glyph_bounds: bool, show_handles_multiple_anchors: bool, + /// [`Session::behind_armed`]. + behind_armed: bool, } /// The tool whose radius is General › Corner Radius. @@ -203,8 +205,10 @@ impl Session { return Ok(()); } // A double-click or triple-click after the switch is the new tool's, also when the switch - // comes back to the tool a Cmd press was lent from. + // comes back to the tool a Cmd press was lent from. Select Behind is armed again by the + // next Cmd press. self.press_lent = None; + self.behind_armed = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state). @@ -366,6 +370,22 @@ impl Session { use_preview_bounds: p.use_preview_bounds, type_glyph_bounds: p.type_glyph_bounds, show_handles_multiple_anchors: p.show_handles_multiple_anchors, + behind_armed: self.behind_armed(), + } + } + + /// Has a Cmd press with the Selection tool in the active document armed Select Behind, with + /// Cmd held since? Then a Cmd-click over the selection selects the object behind it (Selection + /// & Anchor Display › Command Click to Select Objects Behind); the first Cmd press is lent to + /// Direct Selection or Group Selection. + pub fn behind_armed(&self) -> bool { + self.behind_armed.is_some_and(|doc| doc == self.active().map(|d| d.uid)) + } + + /// Cmd let go ends Select Behind's arming ([`Self::behind_armed`]). + fn note_cmd_held(&mut self, mods: &Mods) { + if !mods.cmd { + self.behind_armed = None; } } @@ -374,6 +394,7 @@ impl Session { /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + self.note_cmd_held(mods); let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; let lent = match p { _ if !lends => None, @@ -387,7 +408,8 @@ impl Session { /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when /// the Selection tool keeps a Cmd press on a selected object to select the object behind it - /// (Selection & Anchor Display › Command Click to Select Objects Behind). + /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd + /// press armed ([`Self::behind_armed`]). fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { let id = self.lent_tool(self.tool.id(), mods)?; let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); @@ -629,6 +651,7 @@ impl Session { double_click_isolate: self.prefs.double_click_to_isolate, double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, select_behind: self.prefs.ctrl_click_selects_behind, + behind_armed: self.behind_armed(), highlight_anchors: self.prefs.highlight_anchors_on_hover, snap_tolerance: self.prefs.snap_to_point_tolerance, handles_multiple: self.prefs.show_handles_multiple_anchors, @@ -921,7 +944,13 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); + self.note_cmd_held(&ev.mods); + // A Cmd press with the Selection tool, lent or not, arms Select Behind for the next one. + let arms = ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.tool.id() == "selection"; let (ev, settled) = self.lend_selection_tool(ev, view)?; + if arms { + self.behind_armed = Some(self.active().map(|d| d.uid)); + } let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -1220,6 +1249,7 @@ impl Session { } fn tool_key_now(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result> { + self.note_cmd_held(&mods); // 1–4 pick the active perspective plane while the grid is shown. if let Some(plane) = self.plane_key(key) { self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?; @@ -1460,6 +1490,7 @@ impl Session { /// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { + self.note_cmd_held(&mods); // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; @@ -1887,7 +1918,12 @@ impl Session { // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), // The place cursor's file, read within the roots of whoever loaded the cursor. - Action::Exec(cmd, p) if cmd == "file.place" => { + Action::Exec(cmd, mut p) if cmd == "file.place" => { + if let Some(params) = p.as_object_mut() { + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + params.remove(key); + } + } let roots = self.place_queue_roots.clone(); if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { ui.push(UiRequest::Status(w.to_string())); @@ -1947,14 +1983,14 @@ impl Session { } fn measure_deferred_preview(&mut self, cmd: &str, p: &Value) -> Option { - let (snapshot, selection, revision, paint, interaction_fields) = { + let (snapshot, selection, isolation, revision, paint, interaction_fields) = { let st = self.active()?; let it = st.interaction.as_ref()?; if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) { return None; } let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed); - (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) + (st.doc.clone(), st.selection.clone(), st.isolation, st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default(); @@ -1970,6 +2006,8 @@ impl Session { if let Ok(st) = self.doc_mut() { st.doc = snapshot; st.selection = selection; + // A measured preview that removed the isolated object leaves isolation mode as it was. + st.isolation = isolation; st.revision = revision; if let Some(it) = &mut st.interaction { it.preview = interaction_fields.0; diff --git a/crates/engine/tests/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/data.rs b/crates/eps/src/import/data.rs index ade850a21e..09f7531ff1 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -21,3 +21,5 @@ mod ops; mod pixels; pub(crate) use filters::Stream; +#[cfg(test)] +pub(crate) use ops::measured; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index f5d45449f2..e9bf596eb3 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -8,6 +8,23 @@ use super::{ /// Most bytes one filter or image reads. pub(super) const MAX_DATA: usize = 1 << 28; +/// Decoded bytes the measuring of an image's data left out charges one operation for. A program's +/// budget grows by 64 operations for each byte of it, so the data of one image compressed up to +/// 1024 to 1 is measured within what its own compressed bytes add. +const MEASURED_PER_OP: usize = 16; + +#[cfg(test)] +thread_local! { + /// How many decoded bytes the measuring of images' data left out on this thread decoded. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn measured() -> u64 { + MEASURED.get() +} + /// Most data sources one image may name (a DeviceN space has up to 32 components). const MAX_SOURCES: usize = 32; /// The longest chain of filters over one pending file (real programs stack two or three). @@ -538,10 +555,10 @@ impl Interp<'_> { // it was; the import goes on without the image either way. let Some(first) = chain.first() else { return }; // Measuring decompresses the data, which is charged by the bytes decoded (one operation - // per 256, as `spend_bytes` charges) and stops at what the budget still pays for: - // data measured again and again (a reusable stream reset in a loop) runs out of the - // budget instead of being decoded in full on every pass. - let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX); + // per [`MEASURED_PER_OP`]) and stops at what the budget still pays for: data measured + // again and again (a reusable stream reset in a loop) runs out of the budget after a + // few passes instead of being decoded in full on every pass. + let most = usize::try_from(self.ops_left().saturating_mul(MEASURED_PER_OP as u64)).unwrap_or(usize::MAX); let (used, decoded) = match &from { Some(r) => match &*r.borrow() { Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most), @@ -549,7 +566,9 @@ impl Interp<'_> { }, None => encoded_len(first, self.lex.data(), most), }; - let paid = self.spend_bytes(decoded).is_ok(); + #[cfg(test)] + MEASURED.set(MEASURED.get().saturating_add(decoded as u64)); + let paid = self.spend((decoded / MEASURED_PER_OP) as u64).is_ok(); let Some(used) = used.filter(|_| paid) else { *f.borrow_mut() = Stream::Pending { chain, from }; return; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 2cba146548..1ef5706e68 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -184,10 +184,10 @@ impl ReadText { self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() } - /// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]). - fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap) -> Option<&Texts> { + /// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]). + fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns)); + let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints)); self.texts.insert(texts).as_ref() } } @@ -336,7 +336,7 @@ pub(super) fn build_weighing( placed_pages, envelopes_drawn, styles_read, - text_patterns, + text_paints, canvas_scale, symbols_own_size, xml_ids, @@ -497,7 +497,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_patterns); + let texts = text.texts_with(data, text_paints); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 0ba6c600d5..011cb86ce3 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,6 +7,7 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; +use crate::import::data::measured; use crate::import::graphics::{GState, Out, tilings_compared}; use crate::import::interp::Interp; use crate::import::obj::Obj; @@ -1230,16 +1231,19 @@ fn read_within(body: &str, secs: u64) -> crate::Imported { /// [`read_soon`], with how many patterns the tiling pattern lookups compared while reading. fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { - read_counting(body, NEVER_ENDS) + let (read, compared, _) = read_counting(body, NEVER_ENDS); + (read, compared) } -/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading. -fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64) { +/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and +/// how many decoded bytes the measuring of images' data left out decoded. +fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send((import(&ps), tilings_compared())).ok()); - let (read, compared) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); - (read.unwrap(), compared) + std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok()); + let (read, compared, measured) = + rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); + (read.unwrap(), compared, measured) } /// Runs the program of `body` in an interpreter of its own on the 100 × 100 page of [`eps`]'s @@ -1264,9 +1268,15 @@ fn run_looking(body: &str, look: fn(&Interp) -> T) -> T { /// (`search_in_a_loop_runs_out_of_the_budget` searches about 3 GB, 14 s on a fast desktop), so the /// limit here only catches a program that never stops. pub(super) fn runs_out_of_budget(body: &str) { - let r = read_within(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); + runs_out_of_budget_measuring(body); +} + +/// [`runs_out_of_budget`] → how many decoded bytes the measuring of images' data left out decoded. +pub(super) fn runs_out_of_budget_measuring(body: &str) -> u64 { + let (r, _, measured) = read_counting(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); assert_eq!(objects(&r.document).len(), 1, "{body}: {:?}", r.warnings); assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{body}: {:?}", r.warnings); + measured } /// A large file that runs far more operations than a small one may, but only a few hundred for diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index a9385f8eff..6830fb5b41 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -670,14 +670,16 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { /// Measuring the data of an image too large to hold decompresses it, and that is charged to the /// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed /// zeros is left out and measured again each time a loop runs the stream from its start, runs out -/// of the budget. +/// of the budget after it measured the data in full more than once and at most five times. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { let mut program = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); - super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + let measured = + super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured"); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 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..d61d8e39f5 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -673,9 +673,9 @@ impl PathData { /// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured /// by its control points. /// - /// Walks the segments in place, without building the path: the same segments in the same order, - /// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with - /// no segment, is `Rect::ZERO`, as there). + /// Walks the segments in place, without building the path: the same segments in the same order + /// as `curve_bounds(&self.to_bezpath())`. A subpath of one anchor has no segment, and the box + /// also holds that anchor's point, so a path of lone anchors measures the box around them. pub fn bounds(&self) -> Option { if self.is_empty() { return None; @@ -685,8 +685,26 @@ impl PathData { { return Some(Rect::from_points(a.p, a.p)); } + Some(self.measured(|_| true).unwrap_or_default()) + } + /// The box of what a stroke along the path draws, before the stroke's own reach: its segments, + /// as in [`PathData::bounds`], and the lone anchors a stroke draws. A lone anchor of an open + /// subpath draws nothing. A lone anchor of a closed subpath draws a dot when `dots` is set, as + /// a round or projecting cap does, and nothing otherwise. `None` when the path draws nothing. + pub fn drawn_bounds(&self, dots: bool) -> Option { + self.measured(|sp| dots && sp.closed) + } + /// The box of the segments and of the lone anchors of the subpaths `lone` keeps. + fn measured(&self, lone: impl Fn(&SubPath) -> bool) -> Option { let mut bbox: Option = None; for sp in &self.subpaths { + if sp.segment_count() == 0 + && lone(sp) + && let Some(a) = sp.anchors.first() + { + let lone = Rect::from_points(a.p, a.p); + bbox = Some(bbox.map_or(lone, |bb| bb.union(lone))); + } MEASURED_SEGMENTS.set(MEASURED_SEGMENTS.get().saturating_add(sp.segment_count() as u64)); for i in 0..sp.segment_count() { let c = sp.segment(i); @@ -704,7 +722,7 @@ impl PathData { bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); } } - Some(bbox.unwrap_or_default()) + bbox } /// Bounds including control handles (used for quick culling). pub fn control_bounds(&self) -> Option { @@ -843,6 +861,28 @@ pub fn curve_bounds(path: &BezPath) -> Rect { path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)).unwrap_or_default() } +/// The box of what a stroke along `path` draws before the stroke's own reach, as +/// [`PathData::drawn_bounds`] measures the path it stands for: the box of its segments, as in +/// [`curve_bounds`], and with `dots` the point of each closed subpath that has no segment, which a +/// round or projecting cap draws as a dot. `None` when the path draws nothing. +pub fn drawn_curve_bounds(path: &BezPath, dots: bool) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + if !dots { + return bbox; + } + let els = path.elements(); + for (r, closed) in crate::bez::subpaths(path) { + if closed + && kurbo::segments(els[r.clone()].iter().copied()).next().is_none() + && let Some(p) = els[r.start].end_point() + { + let dot = Rect::from_points(p, p); + bbox = Some(bbox.map_or(dot, |bb| bb.union(dot))); + } + } + bbox +} + /// The box of `seg` as kurbo's `bounding_box` measures it (its start, end and extrema), except /// that a segment with a control point whose x or y is not finite or is larger in size than /// `f64::MAX / 16` is measured by its control points. The box then holds every point the segment @@ -873,7 +913,8 @@ mod tests { use super::*; /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, - /// for lines, curves, open and closed subpaths, lone anchors and empty subpaths. + /// joined with the point of each lone anchor, for lines, curves, open and closed subpaths, lone + /// anchors and empty subpaths. #[test] fn bounds_match_the_bezpath_bit_for_bit() { use proptest::prelude::*; @@ -881,11 +922,10 @@ mod tests { if pd.is_empty() { return None; } - if pd.anchor_count() == 1 { - let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?; - return Some(Rect::from_points(a.p, a.p)); - } - Some(curve_bounds(&pd.to_bezpath())) + let bp = pd.to_bezpath(); + let segments = bp.segments().next().is_some().then(|| curve_bounds(&bp)); + let lone = pd.subpaths.iter().filter(|s| s.segment_count() == 0).filter_map(|s| s.anchors.first()).map(|a| Rect::from_points(a.p, a.p)); + lone.chain(segments).reduce(|bb, r| bb.union(r)) } let bits = |r: Option| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits)); let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)]; @@ -898,11 +938,28 @@ mod tests { let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + // The kurbo path the anchors stand for draws the same box. + for dots in [false, true] { + prop_assert_eq!(bits(drawn_curve_bounds(&pd.to_bezpath(), dots)), bits(pd.drawn_bounds(dots))); + } }); - // Two lone anchors: no segment, as the path has none. + // Two lone anchors: the path has no segment, and the box spans the two points. let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); - assert_eq!(lone.bounds(), Some(Rect::ZERO)); + assert_eq!(lone.bounds(), Some(Rect::new(5.0, 1.0, 9.0, 5.0))); assert_eq!(bits(lone.bounds()), bits(reference(&lone))); + // A lone anchor beside a segment widens the segment's box to reach it. + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(4.0, 2.0)], false); + let beside = PathData::new(vec![line.clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], false)]); + let segment_only = PathData::single(line).bounds().unwrap_or_default(); + let both = beside.bounds().unwrap_or_default(); + assert!(both.x1 >= 20.0 && both.y0 <= -3.0, "{both:?} leaves out the lone anchor at (20, -3)"); + assert_eq!(both.union(segment_only), both, "{both:?} leaves out part of the segment's box {segment_only:?}"); + // What a stroke draws leaves out the open lone anchor, and a closed one without dots. + assert_eq!(beside.drawn_bounds(true), Some(segment_only), "an open lone anchor draws nothing"); + let dot = PathData::new(vec![beside.subpaths[0].clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], true)]); + assert_eq!(dot.drawn_bounds(true), dot.bounds(), "a closed lone anchor draws a dot"); + assert_eq!(dot.drawn_bounds(false), Some(segment_only), "without dots, a closed lone anchor draws nothing"); + assert_eq!(lone.drawn_bounds(false), None, "lone anchors alone draw nothing"); // A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own. let nan = Point::new(f64::NAN, 1.0); let closed = |pts: &[Point]| SubPath::polyline(pts, true); diff --git a/crates/js/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/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f2444bc019..6a91df88e9 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1256,7 +1256,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -2006,6 +2006,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), + ( + "ui.failedPlugins", + "Plug-ins That Didn't Load…", + "", + "{} Object › Plug-ins › Plug-ins That Didn't Load…: list the plug-in files that didn't load in this session, each by its file name with why (plugin.list's failed), at most 50 and a count of the others (dialog `pluginsFailed`); Retry All loads them again (plugin.retry) and the status bar says how many loaded, Close changes nothing → {pending: \"pluginsFailed\", failed: n}. Disabled, and an error, while no plug-in failed to load", + ), ( "plugin.cancelRuns", "Cancel Plug-in Run", diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs index 6eab34d886..708f386958 100644 --- a/crates/metafile/src/encode.rs +++ b/crates/metafile/src/encode.rs @@ -32,7 +32,7 @@ pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, fn convert(op: scene::Op, kind: Kind) -> Op { match op { - scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Fill { path, rule, rgb, .. } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, scene::Op::Stroke { mut path, pen } => { let dash = pen.dash.and_then(|dash| { let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; @@ -78,7 +78,7 @@ mod tests { path.line_to((7.0, 45.0)); path.close_path(); let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; - let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let plain = scene::Pen { rgb: [30, 60, 90], paint: None, width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; let region = Rect::new(0.0, 0.0, 50.0, 50.0); diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 645eb30c11..df23cbb073 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,6 +22,9 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! +//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other +//! formats. +//! //! The app walks its document and maps its drawing operations to the shared writers. #[cfg(test)] @@ -111,6 +114,88 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, + }, + Stroke { + path: vectorcraft_geom::BezPath, + rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: the one colour of a gradient or pattern). + paint: Option, + /// Points. + width: f64, + cap: vectorcraft_doc::LineCap, + join: vectorcraft_doc::LineJoin, + /// The miter limit, as a multiple of the width. + miter: f64, + /// A dash pattern that draws dashes (points). + dash: Option, + }, +} + +/// The visible art of a document, layer by layer ([`painted_layers`]). +#[derive(Clone, Debug, Default)] +pub struct PaintedLayers { + /// Each top-level layer's name (empty when it has none) and its fills and strokes in + /// paint order, in the document's order of layers (the bottom layer first). + pub layers: Vec<(String, Vec)>, + /// What was approximated or left out, as the WMF writer reports it. + pub warnings: Vec, + /// Visible images that could be decoded were left out (one that can't be decoded has its own + /// warning). + pub images: bool, + /// The swatches the paints name: the document's, and those of the documents it places. + pub swatches: Vec, +} + +/// The visible art of `doc` over `region` as fills and strokes, one list for each top-level +/// layer, taken as the WMF writer takes it: live effects applied, type as glyph outlines, +/// gradients and patterns as one colour, clipping masks not applied, and strokes a pen can't draw +/// (aligned inside or outside, width profiles, arrowheads) as their filled outlines. Images are +/// left out. An empty region is an error. +pub fn painted_layers(doc: &Document, region: Rect) -> Result { + check_regions(&[region])?; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (by_layer, mut warnings) = scene::Scene::new(doc, region.abs(), false).run_by_layer(); + let mut out = PaintedLayers::default(); + for (layer, ops) in doc.layers.iter().zip(by_layer) { + let mut painted = Vec::with_capacity(ops.len()); + for op in ops { + match op { + scene::Op::Fill { path, rule, rgb, paint } => painted.push(Painted::Fill { path, rule, rgb, paint }), + scene::Op::Stroke { path, pen } => painted.push(Painted::Stroke { + path, + rgb: pen.rgb, + paint: pen.paint, + width: pen.width, + cap: pen.cap, + join: pen.join, + miter: pen.miter, + dash: pen.dash, + }), + scene::Op::Image { .. } => out.images = true, + scene::Op::Clip { .. } | scene::Op::Unclip => {} + } + } + out.layers.push((layer.name.clone().unwrap_or_default(), painted)); + } + // The images are left out, so how a distorted one would have been written does not apply. An + // image that can't be decoded keeps its warning: it is missing either way. + warnings.retain(|w| w != scene::DISTORTED_IMAGES_NOTE); + out.warnings = warnings; + out.swatches = doc.swatches_iter().cloned().collect(); + Ok(out) +} + /// A metafile read into a document. #[derive(Clone, Debug)] pub struct Imported { diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 3c280822b3..8adbd5e9ed 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -44,11 +44,15 @@ const INSIDE_TOL: f64 = 1e-6; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning about how distorted images are written. +pub(crate) const DISTORTED_IMAGES_NOTE: &str = DISTORTED_IMAGES; /// A stroke as a pen draws it. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Pen { pub rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + pub paint: Option, /// Points. pub width: f64, pub cap: LineCap, @@ -65,6 +69,8 @@ pub(crate) enum Op { path: BezPath, rule: FillRule, rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + paint: Option, }, Stroke { path: BezPath, @@ -104,6 +110,11 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } +/// `p` when it is a solid paint. +fn solid(p: &Paint) -> Option { + matches!(p, Paint::Solid { .. }).then(|| p.clone()) +} + fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -169,6 +180,18 @@ impl<'a> Scene<'a> { (self.ops, self.warnings) } + /// The operations of each top-level layer of the document, in its paint order, and the + /// warnings. Unlike [`Scene::run`], nothing is clipped to the region. + pub fn run_by_layer(mut self) -> (Vec>, Vec) { + let doc = self.doc; + let mut layers = Vec::with_capacity(doc.layers.len()); + for l in &doc.layers { + self.node(l, false); + layers.push(std::mem::take(&mut self.ops)); + } + (layers, self.warnings) + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -397,7 +420,7 @@ impl<'a> Scene<'a> { fn flat_fill(&mut self, bp: &BezPath, rule: FillRule, paint: &Paint, opacity: f32) { let Some(rgb) = self.flat(paint) else { return }; self.check_opacity(opacity); - self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); + self.ops.push(Op::Fill { path: bp.clone(), rule, rgb, paint: solid(paint) }); } /// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's @@ -485,7 +508,15 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.flat(&st.paint) else { return }; self.check_opacity(st.opacity); - let pen = Pen { rgb, width: st.width, cap: st.cap, join: st.join, miter: st.miter_limit, dash: st.dash.clone().filter(|d| d.is_dashed()) }; + let pen = Pen { + rgb, + paint: solid(&st.paint), + width: st.width, + cap: st.cap, + join: st.join, + miter: st.miter_limit, + dash: st.dash.clone().filter(|d| d.is_dashed()), + }; self.ops.push(Op::Stroke { path: bp.clone(), pen }); } @@ -601,7 +632,7 @@ fn merge_tiles(ops: &mut Vec, starts: &[usize]) -> bool { if shape.is_empty() || !rest.iter().all(same) { return false; } - let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb }).collect(); + let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb, paint: None }).collect(); for tile in &tiles { for (op, (path, _, _)) in merged.iter_mut().zip(tile) { if let Op::Fill { path: all, .. } = op { @@ -630,7 +661,7 @@ fn plain_fills(ops: &[Op]) -> Option> { inner .iter() .map(|op| match op { - Op::Fill { path, rule, rgb } => Some((path.clone(), *rule, *rgb)), + Op::Fill { path, rule, rgb, .. } => Some((path.clone(), *rule, *rgb)), _ => None, }) .collect() @@ -741,9 +772,11 @@ mod merge_tests { #[test] fn a_clip_that_cuts_its_fill_is_kept() { let clip = Op::Clip { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero }; - let past = Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let past = + Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert!(plain_fills(&[clip.clone(), past, Op::Unclip]).is_none()); - let within = Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let within = + Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert_eq!(plain_fills(&[clip, within, Op::Unclip]).map(|f| f.len()), Some(1)); } } diff --git a/crates/pdf/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..9fc233e51c 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -65,6 +65,14 @@ pub fn approved(plugin: &Plugin) -> bool { !m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions())) } +/// Tests: what runs before an install waits for the plug-ins, given the plug-in's id. +#[cfg(test)] +type InstallHook = Arc; + +/// Tests: runs right before [`install`] waits for the plug-ins' write lock. +#[cfg(test)] +static BEFORE_INSTALL_LOCK: Mutex> = Mutex::new(None); + /// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists /// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and /// the plug-in installed under its id, the grants and the revision stay as they were. @@ -72,6 +80,13 @@ pub fn install(plugin: Plugin) -> Result> { // The revision moves while the write lock is held, so a cache that reads the new revision and // then the plug-ins finds the new plug-in among them. The approval is checked while it is held // too. + #[cfg(test)] + { + let hook = BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(plugin.id()); + } + } let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner()); if !approved(&plugin) { return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", "))); @@ -518,6 +533,15 @@ impl FolderLoad { Self::list_on(dir, allow, None) } + /// [`FolderLoad::list`] for the one file `file` of a folder, without listing the folder: a file + /// that is no longer there is reported as failed. + pub fn list_file( + file: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + ) -> Result { + Self::list_found(Ok((vec![file.to_path_buf()], 0)), allow, None) + } + /// Starts the loads, unless they started already. pub fn start(&mut self) { self.changes.start(); @@ -530,6 +554,16 @@ impl FolderLoad { dir: &std::path::Path, allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, workers: Option, + ) -> Result { + Self::list_found(Err(dir), allow, workers) + } + + /// [`FolderLoad::list_on`] for the files of folder `Err(dir)`, or for the files and the count of + /// files left out given as `Ok`. + fn list_found( + found: std::result::Result<(Vec, usize), &std::path::Path>, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + workers: Option, ) -> Result { use crate::loader::{Job, Loads}; use crate::safe_mode::{self, Item}; @@ -537,7 +571,10 @@ impl FolderLoad { // A change made elsewhere once the folder starts being listed is one the load doesn't undo. let mut changes = LoadChanges::default(); changes.start(); - let (found, left_out) = folder_files(dir)?; + let (found, left_out) = match found { + Ok(found) => found, + Err(dir) => folder_files(dir)?, + }; let allow = std::sync::Arc::new(allow); let mut files = Vec::with_capacity(found.len()); let mut jobs = Vec::new(); @@ -718,15 +755,24 @@ mod tests { let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap(); let id = plugin.id().to_string(); + let (waits, install_waits) = std::sync::mpsc::channel(); + let ours = id.clone(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &str| { + if p == ours { + let _ = waits.send(()); + } + })); let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner()); let before = revision(); let installing = std::thread::spawn(move || install(plugin)); - let moved = (0..1_000_000).any(|_| { - std::thread::yield_now(); - revision() != before - }); + // The install has done everything it does before it waits for the set, which the test holds. + let reached = install_waits.recv(); + let moved = revision() != before; drop(held); - installing.join().unwrap().unwrap(); + let installed = installing.join(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = None; + installed.unwrap().unwrap(); + assert!(reached.is_ok(), "the install never asked for the set"); assert!(!moved, "the revision changed while the install waited for the set"); assert!(revision() > before && remove(&id)); } @@ -1117,46 +1163,40 @@ mod tests { let first = dir.join("a.wasm"); let (go, a_waits) = std::sync::mpsc::channel::<()>(); let a_waits = Mutex::new(a_waits); - let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let (reached, a_reached) = std::sync::mpsc::channel::<()>(); let held = first.clone(); - let saw = seen.clone(); let _hook = Hooked::set(move |p| { - saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf()); if p == held { + let _ = reached.send(()); let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv(); } }); // Two workers, so the other files load while the first one waits. - let loading = std::thread::spawn({ - let dir = dir.clone(); - move || { - let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?; - load.start(); - while !load.done() { - load.wait(); - load.install_ready(|_| false); - } - Ok::<_, Error>(load.finish()) - } - }); - // The other two files load on the other worker while the first one waits: their loads have - // started (the hook saw them) and ended (the launch marker list no longer has them). + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap(); + load.start(); + // Bound after `load`, so a failing assertion lets the first file go before dropping `load` + // waits for it. + let go = go; + a_reached.recv().unwrap(); + // The other two files load on the other worker while the first one waits: their outcomes + // come in, and the launch marker no longer names them. + let others = [load.loads.record_next(), load.loads.record_next()]; let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm"))); - let finished = |p: &std::path::Path| { + let named = |p: &std::path::Path| { let item = crate::safe_mode::Item::file(p.display().to_string()); - seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) + crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) }; - // Looked at a bounded number of times, and given up when the load ends first. - let reached = (0..10_000_000).any(|_| { - std::thread::yield_now(); - loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2])) - }); - assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited"); - assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); + assert!(others == [Some(1), Some(2)] && !named(&all[1]) && !named(&all[2]), "the other files didn't load meanwhile: {others:?}"); + let early = load.install_ready(|_| false); + assert!(!load.done(), "the load ended while the first file waited"); + assert!(early.is_empty() && ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); go.send(()).unwrap(); - let r = loading.join().unwrap(); + while !load.done() { + load.wait(); + load.install_ready(|_| false); + } + let r = load.finish(); std::fs::remove_dir_all(&dir).unwrap(); - let r = r.unwrap(); assert_eq!(r.loaded, ids.to_vec(), "{r:?}"); let serials: Vec = ids.iter().map(|id| get(id).unwrap().serial()).collect(); assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}"); diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 176828fae2..0a7416d124 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1,14 +1,14 @@ //! The plug-in ABI end to end: the example Desaturate plug-in, and hostile modules (infinite //! loops, memory bombs, out-of-bounds access, bad manifests and outputs…), which must all fail -//! with an error, quickly. +//! with an error, within their instruction budget. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::time::{Duration, Instant}; - use serde_json::{Value, json}; use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{ + Error, FUEL_SLICE, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl, +}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -30,11 +30,16 @@ fn ok_module(run: &str) -> Vec { const INPUT: &str = r#"{"objects":[]}"#; -/// Runs `bytes` on an empty input; returns the error and how long it took. -fn run_err(bytes: &[u8], limits: Limits) -> (Error, Duration) { - let t = Instant::now(); +/// Runs `bytes` on an empty input → the error. +fn run_err(bytes: &[u8], limits: Limits) -> Error { let r = Plugin::load(bytes, limits).and_then(|p| p.run(INPUT.as_bytes(), b"{}")); - (r.expect_err("hostile module must fail"), t.elapsed()) + r.expect_err("hostile module must fail") +} + +/// Two slices of instructions and nothing per input byte: a run that is not stopped between the +/// first and the second slice ends with the instruction budget. +fn two_slices() -> Limits { + Limits { fuel_base: 2 * FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() } } #[test] @@ -73,6 +78,39 @@ fn example_desaturate_moves_every_colour_model_to_grey() { assert!(matches!(vectorcraft_plugins::objects::decode(&none), Err(Error::Failed(m)) if m.contains("Select some paths"))); } +/// A Desaturate run changes colours only: a live shape with fractional coordinates keeps its path +/// exactly and stays live. +#[test] +fn example_desaturate_keeps_the_geometry_exactly() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Document, LiveShape, Node, NodeKind}; + use vectorcraft_geom::{Affine, PathData, Point, SubPath}; + use vectorcraft_plugins::objects; + let p = Plugin::load(DESATURATE, Limits::default()).unwrap(); + let mut d = Document::new(2000.0, 2000.0); + let layer = d.layers[0].id; + let points: Vec = (1..1000).map(|k| f64::from(k) * 1.234_567_890_123_456_7 / 7.0 + 0.1).map(|x| Point::new(x, x / 3.0)).collect(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0); + let mut n = Node::path(d.alloc_id(), PathData::single(SubPath::polyline(&points, true)), red.clone()); + if let NodeKind::Path { live, .. } = &mut n.kind { + *live = Some(Box::new(LiveShape::Rectangle { + w: 10.0 / 3.0, + h: 20.0 / 7.0, + radii: [0.0; 4], + radii_relative: false, + kinds: Default::default(), + xf: Affine::translate((0.1, 1.0 / 3.0)), + })); + } + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let before = d.node(id).unwrap().kind.clone(); + let out = p.run(&objects::encode_input(&d, &[id]), b"{}").unwrap(); + objects::apply_output(&mut d, &[id], objects::decode(&out).unwrap(), None, &|fx, _| Ok(fx.to_vec())).unwrap(); + let after = d.node(id).unwrap(); + assert!(after.kind == before, "the path or its live shape changed"); + assert!(after.appearance != red, "the fill was not desaturated"); +} + #[test] fn input_and_params_reach_the_plugin_and_output_comes_back() { let p = Plugin::load(&build(&tpl::module(MANIFEST, tpl::ECHO, "", 1)), Limits::default()).unwrap(); @@ -86,37 +124,49 @@ fn input_and_params_reach_the_plugin_and_output_comes_back() { assert_eq!(fixed.run(input, b"{}").unwrap(), br#"{"objects":[]}"#); } +/// Each hostile module fails with the error for what it did. The ones that never end stop at +/// their instruction budget, not at the time budget, so how long they run depends on the +/// instructions they are given and not on the machine's speed. #[test] -fn hostile_modules_fail_quickly() { - let quick = Duration::from_secs(5); - let cases: Vec<(&str, Vec)> = vec![ - ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)")), - ("memory.grow bomb, then trap", ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable")), - ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)")), - ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)")), - ("trap", ok_module("unreachable")), - ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)")), - ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))")), - ("error code", ok_module("(i64.const -7)")), - ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)")), - ("huge output", ok_module("(i64.const 0x7fffffff00000000)")), +fn hostile_modules_fail_within_their_budget() { + let budget = "plug-in exceeded its instruction budget"; + let cases: Vec<(&str, Vec, &str)> = vec![ + ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)"), budget), + ( + "memory.grow bomb, then trap", + ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable"), + "plug-in trapped: wasm `unreachable`", + ), + ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)"), budget), + ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)"), "plug-in trapped: out of bounds memory access"), + ("trap", ok_module("unreachable"), "plug-in trapped: wasm `unreachable`"), + ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)"), "plug-in trapped: integer divide by zero"), + ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))"), "plug-in trapped: call stack exhausted"), + ("error code", ok_module("(i64.const -7)"), "plug-in failed: vc_run returned error code -7"), + ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)"), "plug-in ABI: the output points outside memory"), + ("huge output", ok_module("(i64.const 0x7fffffff00000000)"), "plug-in exceeded its output size"), ( "wrong ABI version", build(&tpl::module(MANIFEST, "(i64.const 0)", "", 1).replace("(result i32) (i32.const 1))", "(result i32) (i32.const 2))")), + "plug-in ABI: vc_abi_version returned 2", ), - ("bad manifest", module("not json", "(i64.const 0)", "")), - ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", "")), - ("manifest of the wrong kind", module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", "")), - ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)")), + ("bad manifest", module("not json", "(i64.const 0)", ""), "plug-in manifest: "), + ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", ""), "plug-in manifest: invalid id \"a b\""), + ( + "manifest of the wrong kind", + module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", ""), + "plug-in manifest: manifest: unknown variant `panel`", + ), + ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)"), budget), ( "WASI import", module(MANIFEST, "(i64.const 0)", r#"(import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#), + "plug-in ABI: the module imports `wasi_snapshot_preview1.fd_write`", ), ]; - for (name, bytes) in cases { - let (e, t) = run_err(&bytes, Limits::default()); - assert!(t < quick, "{name} took {t:?}"); - eprintln!("{name}: {e} ({t:?})"); + for (name, bytes, want) in cases { + let e = run_err(&bytes, Limits::default()).to_string(); + assert!(e.starts_with(want), "{name}: {e}"); } } @@ -146,7 +196,7 @@ fn malformed_and_oversized_modules_are_refused() { "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32)", "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32) (return (i32.const -16))", )); - let (e, _) = run_err(&bogus_alloc, Limits::default()); + let e = run_err(&bogus_alloc, Limits::default()); assert!(matches!(e, Error::Abi(_)), "{e}"); } @@ -198,6 +248,22 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() { } } +/// A multi-value `br_table` whose targets all take the same values, with another operand under +/// those values, gives every target the values it was branched with: the run traps unless each +/// branch index returns both of them. +#[test] +fn a_multi_value_branch_table_gives_every_target_its_values() { + let fields = "(func $pick (param $i i32) (result i64 i64) + (block (result i64 i64) (i32.const 7) (i64.const 0x1111) (i64.const 0x2222) (br_table 0 1 0 (local.get $i)))) + (func $check (param $i i32) (local $a i64) (local $b i64) + (call $pick (local.get $i)) (local.set $b) (local.set $a) + (if (i64.ne (local.get $a) (i64.const 0x1111)) (then unreachable)) + (if (i64.ne (local.get $b) (i64.const 0x2222)) (then unreachable)))"; + let run = format!("(call $check (i32.const 0)) (call $check (i32.const 1)) (call $check (i32.const 2)) {}", tpl::ECHO); + let p = Plugin::load(&module(MANIFEST, &run, fields), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + /// A function type with more than 32 parameters or results is refused before any function body is /// validated: the module's extra function has an invalid body, and the error names the limit. A /// type with 32 of each loads. @@ -218,7 +284,7 @@ fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validat #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); + let e = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); assert_eq!(e, Error::Limit("instruction budget".into())); } @@ -261,31 +327,30 @@ fn a_bulk_memory_instruction_at_the_end_of_a_slice_keeps_the_run_s_fuel() { } } +/// The time budget stops a runaway plug-in where the first slice of its instruction budget ends: +/// with a time budget of 0 the deadline has passed on the monotonic clock before the run starts, +/// and an endless loop given two slices ends with the time budget. With the default time budget +/// the same loop runs through both slices and ends with the instruction budget. #[test] fn wall_clock_budget_stops_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - // Wall-clock budget, with an effectively unlimited instruction budget. - let (e, t) = run_err(&spin, Limits { fuel_base: u64::MAX / 4, wall_time_ms: 300, ..Limits::default() }); - assert_eq!(e, Error::Limit("time budget".into())); - assert!(t < Duration::from_secs(3), "{t:?}"); + assert_eq!(run_err(&spin, Limits { wall_time_ms: 0, ..two_slices() }), Error::Limit("time budget".into())); + assert_eq!(run_err(&spin, two_slices()), Error::Limit("instruction budget".into())); } -/// Cancelling stops a run where one slice of its budget ends: an endless loop given all but -/// unlimited instructions comes back `Cancelled` within seconds, where outside a cancelled scope the -/// same module runs until its budget is spent. +/// Cancelling stops a run where one slice of its budget ends: an endless loop given two slices of +/// instructions comes back `Cancelled` at the end of the first, where outside a cancelled scope the +/// same module runs through both and ends with the instruction budget. #[test] fn cancelling_stops_a_run_between_two_slices_of_its_budget() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let p = Plugin::load(&spin, Limits { fuel_base: u64::MAX / 4, ..Limits::default() }).unwrap(); + let p = Plugin::load(&spin, two_slices()).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); token.cancel(); - let t = Instant::now(); let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); assert_eq!(r, Err(Error::Cancelled)); - assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed()); // Outside a cancelled scope the same module still runs to its budget. - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, ..Limits::default() }); - assert_eq!(e, Error::Limit("instruction budget".into())); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); } /// Compiling a plug-in's code takes none of a run's instructions, so a first run takes as many as the @@ -318,7 +383,7 @@ fn a_first_run_takes_no_more_instructions_than_the_next() { fn a_heavy_filter_finishes_what_a_light_one_cannot() { let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; let (light, heavy) = (build(&tpl::spinning(MANIFEST, 100_000_000, INPUT)), build(&tpl::spinning(heavy, 100_000_000, INPUT))); - assert_eq!(run_err(&light, Limits::default()).0, Error::Limit("instruction budget".into())); + assert_eq!(run_err(&light, Limits::default()), Error::Limit("instruction budget".into())); let p = Plugin::load(&heavy, Limits::default()).unwrap(); assert_eq!((p.limits().fuel_base, p.limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); assert_eq!(heavy_terms(), (5, 20)); diff --git a/crates/plugins/tests/fixtures/desaturate.wasm b/crates/plugins/tests/fixtures/desaturate.wasm index 730ec35545..ee58960ca2 100644 Binary files a/crates/plugins/tests/fixtures/desaturate.wasm and b/crates/plugins/tests/fixtures/desaturate.wasm differ diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index 9a580a1b11..ef282e5b4d 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -7,6 +7,8 @@ use std::sync::Arc; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, Rect}; +use crate::placed_document::{LayerMode, enter_layer}; + /// What may draw differently in a document than in its version before an edit ([`changed`]). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Changed { @@ -129,6 +131,8 @@ fn changed_with(old: &Document, new: &Document, renderer: Option<&mut crate::Ren return Changed::Everything; } let mut diff = Diff { old: old.symbol_boxes(), new: new.symbol_boxes(), area: None, renderer, opts, sources: (None, None) }; + // Measured as the frames with `opts` draw ([`crate::Renderer::cross_placed`]). + let _mode = LayerMode { options: opts.dim_templates && !opts.skip_templates, outline: opts.outline, images: new.setup.outline_images }.enter(); diff.children(&old.layers, &new.layers); diff.area.map_or(Changed::Nothing, Changed::Area) } @@ -179,11 +183,20 @@ impl Diff<'_, '_> { } } + /// [`Self::node_in`], the members of a layer that draws in the same mode in both versions + /// measured in that mode ([`LayerMode::inside`]). The two versions of a layer that draw in + /// different modes are each measured in their own ([`Self::bounds`]). + fn node(&mut self, old: &Arc, new: &Arc) { + let modes = LayerMode::now().map(|m| (m.inside(old), m.inside(new))); + let _mode = modes.and_then(|(a, b)| if a == b { b } else { None }).map(LayerMode::enter); + self.node_in(old, new); + } + /// A group or layer that only its members changed in, without a clipping mask or effects of /// its own that draw from all of them, changed where they did. A path or compound path that /// only had anchors moved changed around them ([`moved_anchors`]). Any other object that /// changed counts whole, before and after. - fn node(&mut self, old: &Arc, new: &Arc) { + fn node_in(&mut self, old: &Arc, new: &Arc) { if Arc::ptr_eq(old, new) || self.unseen(Side::Old, old) && self.unseen(Side::New, new) { return; } @@ -228,6 +241,8 @@ impl Diff<'_, '_> { if self.unseen(side, n) { return None; } + // A layer is measured in the mode its Layer Options draw it in. + let _mode = enter_layer(n); let Diff { old, new, renderer, .. } = self; let symbols = match side { Side::Old => old, diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2a554a3d92..dc9b8063de 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -124,7 +124,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { if carry.skipped() { carry.hide_skipped(&mut ran.to_mut().appearance.effects); } - let mut r: Option = (!g.elements().is_empty()).then(|| g.bounding_box()); + let mut r: Option = drawn_box(&g, n.appearance.painted_strokes().any(dotted)); for (j, item) in n.appearance.items.iter().enumerate() { let fx = item_effects(item); if effects::has_geometry(fx) { @@ -134,10 +134,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { { c.hide_skipped(it.effects_mut()); } - if !ig.elements().is_empty() { - let b = ig.bounding_box(); - r = Some(r.map_or(b, |r| r.union(b))); - } + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item))); } } let s = n.appearance.outset(); @@ -324,10 +321,29 @@ fn item_bounds(doc: &Document, n: &Node, item: &AppearanceItem) -> Option if effects::has_geometry(fx) { let ig = apply(fx, &g, &GeomContext { doc: Some(doc), ..GeomContext::of(n) }.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - return (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o)); + return drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o)); } let one = vectorcraft_doc::Appearance { items: vec![item.clone()], ..Default::default() }; - (!g.elements().is_empty()).then(|| one.stroked_bounds(g.bounding_box(), || g.clone())) + drawn_box(&g, item_dots(item)).map(|b| one.stroked_bounds(b, || g.clone())) +} + +/// The box of what `g` draws before the strokes' reach ([`vectorcraft_geom::path::drawn_curve_bounds`]), +/// with the lone anchors of closed subpaths when `dots`; a path that draws nothing is measured by +/// its anchors, as [`Node::visual_bounds`] measures one. `None` for a path with no elements. +pub(super) fn drawn_box(g: &BezPath, dots: bool) -> Option { + vectorcraft_geom::path::drawn_curve_bounds(g, dots) + .or_else(|| g.elements().iter().filter_map(|e| e.end_point()).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b))) +} + +/// Does `s`, a painted stroke, draw a lone anchor of a closed subpath as a dot (a round or +/// projecting cap)? +pub(super) fn dotted(s: &vectorcraft_doc::StrokeLayer) -> bool { + matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square) +} + +/// Does `item` draw lone anchors as dots: a painted stroke with a round or projecting cap? +fn item_dots(item: &AppearanceItem) -> bool { + matches!(item, AppearanceItem::Stroke(s) if paints(item) && dotted(s)) } /// `b` grown by how far raster effects `fx` paint past it, each spreading what the ones before it @@ -382,12 +398,13 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { let mut plain = n.appearance.clone(); plain.items.retain(|i| !(paints(i) && effects::has_geometry(item_effects(i)))); let on_path = !n.appearance.items.iter().any(paints) || plain.items.iter().any(paints); - let mut r = (on_path && !g.elements().is_empty()).then(|| plain.stroked_bounds(g.bounding_box(), || g.clone())); + let dots = plain.painted_strokes().any(dotted); + let mut r = on_path.then(|| drawn_box(&g, dots)).flatten().map(|b| plain.stroked_bounds(b, || g.clone())); let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) }; for item in n.appearance.items.iter().filter(|i| paints(i) && effects::has_geometry(item_effects(i))) { let ig = apply(item_effects(item), &g, &ctx.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - r = vectorcraft_geom::union_opt(r, (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o))); + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o))); } r } diff --git a/crates/render/src/fx/predicates.rs b/crates/render/src/fx/predicates.rs index 08bfceb7f2..f46a109aa7 100644 --- a/crates/render/src/fx/predicates.rs +++ b/crates/render/src/fx/predicates.rs @@ -68,11 +68,13 @@ pub(super) fn evaluates_live(n: &Node) -> bool { /// dots sampled from everything it draws), one with a live-effect plug-in that paints its pieces /// (drawn only while the swatches and patterns they name are in the document), or an image with a /// fill or stroke that follows the outline of its pixels ([`effects::follows_image_pixels`]: the -/// document's pixels for it can change), in it or in the opacity masks of the objects in it. +/// document's pixels for it can change), or a placed document (its file read, or in some Outline +/// frames its crossed box, [`vectorcraft_doc::placed_document::Crossed`]), in it or in the opacity +/// masks of the objects in it. pub(super) fn reads_outside(n: &Node) -> bool { let mut reads = false; n.walk(&mut |c| { - reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. }) + reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_)) || effects::follows_image_pixels(c) || effects::has_revolve(c) || effects::has_solid(c) diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 1bc71d4626..67b80e6b41 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1,4 +1,4 @@ -use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage}; +use super::bounds::{cull_bounds, dotted, drawn_box, effected_path_carrying, node_bezpath, rasterize_stage}; use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry}; use super::pixels::FilterReach; use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted}; @@ -453,7 +453,7 @@ impl Renderer { let rfx = effects::raster_effects(&paints.appearance.effects); // Document-space reach of the painted geometry (strokes, arrowheads…). let outset = n.appearance.outset(); - let reach = g.bounding_box().inflate(outset, outset); + let reach = drawn_box(g, paints.appearance.painted_strokes().any(dotted)).unwrap_or_default().inflate(outset, outset); let bounds = rasterize_bounds(f.symbols, n, &rfx); // Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint. let reach = bounds.map_or(reach, |b| reach.union(b)); @@ -488,9 +488,9 @@ impl Renderer { // A placed document whose effects make no art of their own (raster effects and color // adjustments, which Outline mode does not draw) shows its box crossed as without effects // ([`Self::draw_placed`]). Effects that change geometry (plug-in effects among them, - // [`effects::is_geometry`]), 3D and Pathfinder make art from - // the file's art, which is drawn; Crop Marks and Vector Halftone draw the placed document - // itself among their art. + // [`effects::is_geometry`]), 3D and Pathfinder make art from the crossed box, which the + // frame gives as the placed document's art ([`Self::cross_placed`]), and that art is drawn; + // Crop Marks and Vector Halftone draw the placed document itself among their art. if let NodeKind::PlacedDocument(p) = &a.kind && self.crosses_placed(f) && !effects::has_geometry(&a.appearance.effects) diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 39b6e951b8..9a5eb976e1 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -99,6 +99,88 @@ fn doc_with(r: Rect, fill: Color, effects: Vec<(&str, serde_json::Value)>) -> Do d } +/// A stroked line from (10, 50) to (60, 50) beside a lone anchor at (90, 90), closed or open +/// (`line` false: the lone anchor alone), its stroke 4 pt wide with `cap`, round joins and the +/// object-level `object` and stroke-level `stroke` effects. +fn lone_anchor_doc(line: bool, closed: bool, cap: vectorcraft_doc::LineCap, object: &[Effect], stroke: &[Effect]) -> Document { + use vectorcraft_geom::{PathData, SubPath}; + let mut d = Document::new(100.0, 100.0); + let lone = SubPath::polyline(&[Point::new(90.0, 90.0)], closed); + let subpaths = if line { vec![SubPath::polyline(&[Point::new(10.0, 50.0), Point::new(60.0, 50.0)], false), lone] } else { vec![lone] }; + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + let s = ap.stroke_mut().unwrap(); + (s.cap, s.join) = (cap, vectorcraft_doc::LineJoin::Round); + s.effects = stroke.to_vec(); + ap.effects = object.to_vec(); + let n = Node::path(d.alloc_id(), PathData::new(subpaths), ap); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// The bounds the effects are measured by hold the dot a round or projecting cap draws for a +/// lone anchor of a closed subpath, wherever the effected path is measured: the visual and cull +/// bounds (with the object's or the stroke's own geometry effect) and what Rasterize makes its image +/// over (the path as drawn, and a stroke with a raster effect, with and without a geometry effect +/// of its own). A lone anchor that draws no dot (open, or under a butt cap) leaves them as the line +/// alone has them. +#[test] +fn effect_bounds_hold_a_lone_anchors_dot_only_where_its_cap_draws_one() { + use vectorcraft_doc::LineCap; + let fx = |id: &str, p: serde_json::Value| Effect { id: id.into(), params: p, visible: true }; + // The object's effect moves the dot to (91, 90), the stroke's own effect to (130, 90), and the + // stroke's shadow paints a copy 30 pt below. + let moved = fx("distort.transform", json!({"moveH": 1})); + let far = fx("distort.transform", json!({"moveH": 40})); + let shadow = fx("stylize.dropShadow", json!({"x": 0, "y": 30, "blur": 0})); + // (what, object effects, stroke effects, measure, the center of the lowest dot painted) + type Measure = fn(&Document, &Node) -> Option; + let visual: Measure = |d, n| super::visual_bounds(&d.symbol_boxes(), n); + let cull: Measure = |d, n| super::cull_bounds(&d.symbol_boxes(), n); + let drawn: Measure = |d, n| crate::drawn_bounds(d, n); + type Case = (&'static str, Vec, Vec, Measure, Point); + let cases: [Case; 7] = [ + ("visual, object effect", vec![moved.clone()], vec![], visual, Point::new(91.0, 90.0)), + ("visual, stroke effect", vec![], vec![far.clone()], visual, Point::new(130.0, 90.0)), + ("cull, object effect", vec![moved.clone()], vec![], cull, Point::new(91.0, 90.0)), + ("drawn, object effect", vec![moved.clone()], vec![], drawn, Point::new(91.0, 90.0)), + ("drawn, stroke effect", vec![], vec![far.clone()], drawn, Point::new(130.0, 90.0)), + ("drawn, stroke raster effect", vec![moved.clone()], vec![shadow.clone()], drawn, Point::new(91.0, 120.0)), + ("drawn, stroke geometry and raster effects", vec![], vec![far.clone(), shadow.clone()], drawn, Point::new(130.0, 120.0)), + ]; + for (what, object, stroke, measure, dot) in cases { + for (closed, cap) in [(true, LineCap::Round), (true, LineCap::Square), (true, LineCap::Butt), (false, LineCap::Round)] { + let d = lone_anchor_doc(true, closed, cap, &object, &stroke); + let b = measure(&d, &d.layers[0].children().unwrap()[0]).unwrap(); + if closed && cap != LineCap::Butt { + // The dot is 4 pt across. + assert!(b.x1 >= dot.x + 2.0 - 1e-6 && b.y1 >= dot.y + 2.0 - 1e-6, "{what}, {cap:?}: {b:?} leaves out the dot at {dot:?}"); + } else { + assert!(b.y1 < dot.y - 2.0, "{what}, closed {closed}, {cap:?}: {b:?} reaches toward a lone anchor that draws nothing"); + } + } + } +} + +/// A path of only a lone anchor is measured at that anchor, not at the origin, and an effect that +/// paints around what the path draws (a drop shadow) is drawn over the dot a round cap draws there. +#[test] +fn a_path_of_a_lone_anchor_is_measured_at_its_dot() { + use vectorcraft_doc::LineCap; + let moved = Effect { id: "distort.transform".into(), params: json!({"moveH": 1}), visible: true }; + let d = lone_anchor_doc(false, true, LineCap::Round, std::slice::from_ref(&moved), &[]); + let n = &d.layers[0].children().unwrap()[0]; + for (what, b) in [("visual", super::visual_bounds(&d.symbol_boxes(), n)), ("drawn", crate::drawn_bounds(&d, n))] { + let b = b.unwrap(); + assert!(b.contains(Point::new(91.0, 90.0)) && !b.contains(Point::ZERO), "{what}: {b:?}"); + } + let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 0, "y": 6, "blur": 0}), visible: true }; + let d = lone_anchor_doc(true, true, LineCap::Round, &[moved, shadow], &[]); + let img = render(&d); + assert!(lum(img.pixel(91, 90)) < 200, "the dot is drawn"); + assert!(lum(img.pixel(91, 96)) < 600, "the dot's shadow is drawn: {:?}", img.pixel(91, 96)); +} + fn render(d: &Document) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) } diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 341aa22ff9..2884e9c4d8 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -176,7 +176,8 @@ struct Shown { /// tilings ([`crate::pattern::hash_tiling`]) of the patterns in the fills and strokes of its /// objects and of type's characters, the address of each symbol instance's art, and the address of /// the read of each placed file that [`vectorcraft_doc::PlacedDocument::art`] shows (none before -/// the file is read), and the address of the document's pixels for each image whose +/// the file is read) with whether that art is the crossed box +/// ([`vectorcraft_doc::placed_document::Crossed`]), and the address of the document's pixels for each image whose /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, @@ -214,6 +215,8 @@ fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, NodeKind::PlacedDocument(p) => { let read = vectorcraft_doc::placed_document::read_cached(p); read.as_ref().map(|r| Arc::as_ptr(r) as usize).hash(h); + // The art is the crossed box instead in some Outline frames. + vectorcraft_doc::placed_document::crossed().hash(h); shown.reads.extend(read.as_ref().map(Arc::downgrade)); shown.text = true; shown.placed = true; diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 9ad5b687bb..c3f7caa40b 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -28,7 +28,7 @@ use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use vectorcraft_doc::placed_document::MAX_DEPTH; use vectorcraft_doc::{ImageBlob, Node, PlacedDocument}; @@ -69,6 +69,8 @@ struct Bitmaps { static BITMAPS: LazyLock> = LazyLock::new(Default::default); /// Bitmaps being made. static PENDING: LazyLock>> = LazyLock::new(Default::default); +/// Signaled, under [`PENDING`]'s lock, when the last bitmap being made stops being pending. +static IDLE: Condvar = Condvar::new(); /// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for /// again. static FAILED: LazyLock>> = LazyLock::new(Default::default); @@ -123,6 +125,24 @@ pub fn busy() -> bool { !lock(&PENDING).is_empty() } +/// Bitmap `key` stops being pending; when none is left, [`IDLE`] is signaled. +fn finish(key: &BitmapKey) { + let mut pending = lock(&PENDING); + pending.remove(key); + if pending.is_empty() { + IDLE.notify_all(); + } +} + +/// Wait until no bitmap is being made ([`busy`] is false). +#[cfg(test)] +pub(crate) fn wait_idle() { + let mut pending = lock(&PENDING); + while !pending.is_empty() { + pending = IDLE.wait(pending).unwrap_or_else(PoisonError::into_inner); + } +} + /// Is a bitmap of file `key` being made? #[cfg(test)] pub(crate) fn pending_for(key: &str) -> bool { @@ -237,12 +257,32 @@ thread_local! { static DEPTH: Cell = const { Cell::new(0) }; } +#[cfg(test)] +thread_local! { + /// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. + static DEEPEST: Cell = const { Cell::new(0) }; +} + +/// Start counting how deep this thread draws inside placed documents ([`deepest`]). +#[cfg(test)] +pub(crate) fn reset_deepest() { + DEEPEST.with(|d| d.set(0)); +} + +/// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. +#[cfg(test)] +pub(crate) fn deepest() -> usize { + DEEPEST.with(Cell::get) +} + /// While alive: drawing inside a placed document, one level deeper. struct Inside; impl Inside { fn enter() -> Self { DEPTH.with(|d| d.set(d.get() + 1)); + #[cfg(test)] + DEEPEST.with(|d| d.set(d.get().max(depth()))); Inside } } @@ -257,6 +297,74 @@ fn depth() -> usize { DEPTH.with(Cell::get) } +/// How a frame draws art ([`Renderer::layer_mode`]): whether Layer Options apply (on screen; +/// exports and thumbnails ignore them), whether the art draws in Outline mode, and whether Show +/// Images in Outline Mode is on for it ([`Renderer::shows_outline_images`]). Layers are measured +/// in the mode they draw in, and placed documents are their crossed box in Outline mode without +/// Show Images in Outline Mode ([`vectorcraft_doc::placed_document::Crossed`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct LayerMode { + pub(crate) options: bool, + pub(crate) outline: bool, + pub(crate) images: bool, +} + +thread_local! { + /// The mode of the frame being drawn or measured on this thread ([`LayerMode::enter`]). + static MODE: Cell> = const { Cell::new(None) }; +} + +impl LayerMode { + /// The mode layer `n` draws its art in when its Layer Options change it: a template layer stays + /// in Preview in Outline mode (#1486), and a layer whose Preview is off draws in outline. + /// `None` for other objects and for a layer that draws in this mode. + pub(crate) fn inside(self, n: &Node) -> Option { + let vectorcraft_doc::NodeKind::Layer { preview, template, .. } = &n.kind else { return None }; + if !self.options { + return None; + } + let outline = if *template && self.outline { + false + } else if !preview && !template && !self.outline { + true + } else { + return None; + }; + Some(Self { outline, ..self }) + } + + /// The mode of the frame being drawn or measured on this thread, if any. + pub(crate) fn now() -> Option { + MODE.with(Cell::get) + } + + /// Draw and measure in this mode on this thread until the guard returned is dropped. + pub(crate) fn enter(self) -> InMode { + let crossed = vectorcraft_doc::placed_document::Crossed::set(self.outline && !self.images); + InMode { was: MODE.with(|m| m.replace(Some(self))), _crossed: crossed } + } +} + +/// While alive: art on this thread is drawn and measured in a [`LayerMode`]; once dropped, in the +/// mode before it. +#[must_use] +pub(crate) struct InMode { + was: Option, + _crossed: vectorcraft_doc::placed_document::Crossed, +} + +impl Drop for InMode { + fn drop(&mut self) { + MODE.with(|m| m.set(self.was)); + } +} + +/// Measure layer `n` in the mode its Layer Options draw it in, inside the mode on this thread +/// ([`LayerMode::inside`]), until the guard returned is dropped; `None` when that is the same mode. +pub(crate) fn enter_layer(n: &Node) -> Option { + LayerMode::now()?.inside(n).map(LayerMode::enter) +} + /// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent /// pixels through `view`, the placed documents inside it one level deeper. pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc, w: u16, h: u16, view: Affine) -> Option { @@ -323,7 +431,7 @@ fn run(r: &mut Renderer, mut job: Job) { lock(&FAILED).insert(job.key.clone()); } } - lock(&PENDING).remove(&job.key); + finish(&job.key); }; match scope { Some(scoped) => scoped(&mut body), @@ -356,7 +464,7 @@ mod workers { let key = job.key.clone(); if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() { super::lock(&super::FAILED).insert(key.clone()); - super::lock(&super::PENDING).remove(&key); + super::finish(&key); } } }); @@ -449,8 +557,8 @@ impl Renderer { } /// Draw placed document `p` as its box crossed from corner to corner ([`Self::crosses_placed`]). - /// Its file is still read, as when its art is drawn: the art its effects and its group's effects - /// make comes from the read kept. + /// Its file is still read, as when its art is drawn: once the frame shows images again, the art + /// its effects and its group's effects make comes from the read kept. pub(crate) fn draw_crossed_placed(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) { if let Some(blob) = f.doc.images.get(&p.key) { let _ = read_placed(p, blob); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 3e34f4da9b..065055f96c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -198,6 +198,7 @@ impl Renderer { let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let _crossed = self.cross_placed(&frame); self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { @@ -484,6 +485,7 @@ impl Renderer { let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); + let _crossed = self.cross_placed(&frame); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 1e47dcf70d..b34f562ca1 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -6,6 +6,27 @@ use super::{ }; use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; +use crate::placed_document::{InMode, LayerMode, enter_layer}; +use vectorcraft_doc::placed_document::crossed; + +/// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the +/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in +/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are +/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a +/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no +/// other node has that key. +fn geom_key(a: &Node) -> usize { + let at = std::ptr::from_ref(a) as usize; + match a.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => at, + NodeKind::Layer { .. } => { + at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2) + } + _ => at | usize::from(crossed()), + } +} + +const _: () = assert!(std::mem::align_of::() >= 8, "geom_key keeps three bits below a node's address"); fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { measures_three_d(node) @@ -34,7 +55,7 @@ impl Renderer { if patch.is_some_and(Frame::patch_rejected) { return None; } - let key = Arc::as_ptr(a) as usize; + let key = geom_key(a); if let Some(e) = self.geom.get_mut(&key) && Arc::ptr_eq(&e.node, a) { @@ -53,6 +74,7 @@ impl Renderer { let source = a.extras().trace.is_some().then(|| children.first()).flatten(); for c in children { if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) { + let _mode = enter_layer(c); acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch)); if patch.is_some_and(Frame::patch_rejected) { return None; @@ -158,6 +180,19 @@ impl Renderer { } } + /// How frame `f` draws art ([`LayerMode`]). + pub(crate) fn layer_mode(&self, f: &Frame) -> LayerMode { + LayerMode { options: f.opts.dim_templates && !f.opts.skip_templates, outline: f.opts.outline, images: self.shows_outline_images(f) } + } + + /// Draw and measure art in frame `f`'s mode ([`Self::layer_mode`]) until the guard returned is + /// dropped: placed documents' art ([`vectorcraft_doc::PlacedDocument::art`]) is their box + /// crossed from corner to corner in Outline mode without Document Setup → Show Images in + /// Outline Mode ([`Self::crosses_placed`]), else their file's art. + pub(crate) fn cross_placed(&self, f: &Frame) -> InMode { + self.layer_mode(f).enter() + } + /// When a plug-in has been installed or removed since the last check /// ([`effects::plugin_revision`]), drop what the caches keep from plug-in effects: the effect /// geometry of paths with a plug-in effect, the cull bounds of objects that have one or hold one, @@ -266,6 +301,8 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } + // A layer is measured in the mode its Layer Options draw it in ([`Self::draw_node`]). + let _mode = self.layer_mode(f).inside(a).map(LayerMode::enter); let bounds = self.frame_bounds_of(f, a); if f.patch_rejected() { return true; @@ -377,6 +414,13 @@ impl Renderer { /// Everything [`Self::draw_arc`] does after culling. fn draw_arc_body(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { + // A layer with effects of its own draws them in the mode its Layer Options give it, as + // `draw_node` draws any other layer. + if let Some(mode) = self.layer_mode(f).inside(a) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); + return self.draw_arc_body(ctx, &Frame { opts: &opts, ..*f }, a); + } // Fast path for plain paths: cached geometry, opacity folded into the paint. // A blend mode on a single plain fill applies per draw (exact for one paint operation); // a blend layer would composite the whole viewport. @@ -459,18 +503,15 @@ impl Renderer { // Layer Options on screen: a layer whose Preview is off draws in outline, and Dim Images // fades its images, a template's too (exports and thumbnails, which leave templates out, // ignore both). - if let NodeKind::Layer { preview, dim_images, template, .. } = &n.kind + if let NodeKind::Layer { dim_images, .. } = &n.kind && f.opts.dim_templates && !f.opts.skip_templates { // A template layer stays in Preview while the view is in Outline (and whatever its own // Preview option says): its picture is there to be traced (#1486). - if *template && f.opts.outline { - let opts = RenderOptions { outline: false, ..f.opts.clone() }; - return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); - } - if !preview && !template && !f.opts.outline { - let opts = RenderOptions { outline: true, ..f.opts.clone() }; + if let Some(mode) = self.layer_mode(f).inside(n) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); } if let Some(p) = *dim_images { @@ -763,6 +804,7 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; + let _crossed = self.cross_placed(&frame); // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are // each stroked without a fill or (on a stretched image, the strokes' outlines) filled // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the @@ -843,7 +885,7 @@ impl Renderer { /// Cull bounds of `n` (symbol instances measured by their art box from `symbols`): cached when /// it is a node of the tree being drawn. fn node_bounds(&mut self, symbols: &SymbolBoxes, n: &Node) -> Option { - match self.geom.get(&(n as *const Node as usize)) { + match self.geom.get(&geom_key(n)) { // The entry keeps its node alive, so the address is that node's. Some(e) if std::ptr::eq(Arc::as_ptr(&e.node), n) => e.bounds, _ => fx::cull_bounds(symbols, n), diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 9d11cd6eaf..738fd44488 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -85,31 +85,43 @@ fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node /// Held shut, [`gated_blue_page`] makes the background worker wait before reading a file, so a /// frame drawn meanwhile shows the placeholders whatever the scheduler does (#5152: a fast worker /// could finish between scheduling a bitmap and the frame looking it up again). -static GATE_SHUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static GATE_SHUT: std::sync::Mutex = std::sync::Mutex::new(false); +/// Signaled when the gate opens. +static GATE_OPENED: std::sync::Condvar = std::sync::Condvar::new(); /// The thread drawing while the gate is shut: it never waits (a file read there is drawn exactly). static GATE_HOLDER: std::sync::Mutex> = std::sync::Mutex::new(None); -/// [`blue_page`] once the gate opens (at most 10 s), except on the thread that shut it. Every test -/// here registers it: the first registration stays, so all of them must agree (open, it is +/// [`blue_page`] once the gate opens, except on the thread that shut it. Every test here +/// registers it: the first registration stays, so all of them must agree (open, it is /// `blue_page`). fn gated_blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { let here = std::thread::current().id(); let holder = *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let t = std::time::Instant::now(); - while holder != Some(here) && GATE_SHUT.load(std::sync::atomic::Ordering::SeqCst) && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(1)); + if holder != Some(here) { + let mut shut = GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while *shut { + shut = GATE_OPENED.wait(shut).unwrap_or_else(std::sync::PoisonError::into_inner); + } } blue_page(p, bytes) } -/// Shut the gate for the calling thread's frames. -fn shut_gate() { - *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); - GATE_SHUT.store(true, std::sync::atomic::Ordering::SeqCst); +/// The gate shut by [`shut_gate`]; dropping it opens the gate, also when the test fails while it +/// is shut. +struct Gate; + +impl Drop for Gate { + fn drop(&mut self) { + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false; + GATE_OPENED.notify_all(); + } } -fn open_gate() { - GATE_SHUT.store(false, std::sync::atomic::Ordering::SeqCst); +/// Shut the gate for the calling thread's frames, until the [`Gate`] is dropped. +fn shut_gate() -> Gate { + *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + Gate } /// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their @@ -129,12 +141,9 @@ fn render(d: &Document, progressive: bool) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts) } -/// Wait for the background bitmaps (at most 10 s). +/// Wait for the background bitmaps. fn settle() { - let t = std::time::Instant::now(); - while placed_document::busy() && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + placed_document::wait_idle(); assert!(!placed_document::busy(), "bitmaps still coming"); } @@ -197,16 +206,18 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let r = outline(&d); assert!(inked(&r, 20, 15), "a placed document with a color adjustment is crossed"); assert!(!inked(&r, 50, 20), "and none of its file's art is drawn"); - // A Transform effect reshapes the file's art, read when the crossed box was drawn: its rectangle - // is drawn moved 40 points down to (10, 50)–(90, 90), its bottom edge at y = 90, with no cross - // through it ((20, 55) is on its diagonal) or where the box was. + // A Transform effect reshapes the crossed box: it is drawn moved 40 points down to + // (10, 50)–(90, 90), its bottom edge at y = 90 and crossed ((20, 55) is on its diagonal), with + // nothing where the box was and none of the file's art ((50, 60) is the top edge of the box the + // file places in itself, moved). let mut d = doc_with("outline-cross-4", b"loop"); assert!(inked(&outline(&d), 20, 15), "first drawn crossed"); let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved"); - assert!(!inked(&r, 20, 55), "uncrossed"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved"); + assert!(inked(&r, 20, 55), "crossed"); + assert!(!inked(&r, 50, 60), "without the file's art"); assert!(!inked(&r, 20, 15), "and nothing is drawn where the box was"); // The same when the box was first drawn crossed with a drop shadow. let mut d = doc_with("outline-cross-5", b"loop"); @@ -220,7 +231,125 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved after a drop shadow"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved after a drop shadow"); + assert!(inked(&r, 20, 55), "and crossed"); +} + +#[test] +fn outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // The box (10, 10)–(90, 50) in a group whose Transform effect moves it 40 points down: crossed at + // (10, 50)–(90, 90), whose diagonal from the top left passes (20, 55). The file places itself in + // its middle: moved, the top edge of that box passes (50, 60). + let mut d = doc_with("outline-group-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let mut group = Node::group(NodeId(80), vec![placed]); + let params = serde_json::json!({"moveV": 40}); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = outline(&mut r, &d); + assert!(inked(&crossed, 20, 55), "the moved box is crossed"); + assert!(!inked(&crossed, 50, 60), "without the file's art"); + assert!(!inked(&crossed, 20, 15), "and nothing is drawn where the box was"); + // With Show Images in Outline Mode the same renderer draws the file's art moved, not the art it + // kept for the crossed box, and back again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(!inked(&shown, 20, 55), "with Show Images in Outline Mode the box is not crossed"); + assert!(inked(&shown, 50, 60), "and the file's art is drawn moved"); + assert!(shown.pixels == outline(&mut Renderer::new(), &d).pixels, "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d).pixels == crossed.pixels, "crossed again as at first"); +} + +#[test] +fn a_template_layer_in_outline_mode_draws_a_placed_documents_art_its_effects_reshape() { + // A template layer stays in Preview in Outline mode: the file's blue art moved 40 points down + // by a Transform effect fills (10, 50)–(90, 90), and is not crossed. + let mut d = doc_with("outline-template-1", b"blue"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + if let NodeKind::Layer { template, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *template = true; + } + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the file's art fills the moved box: {:?}", r.pixel(50, 80)); + // The same with the Transform effect on the template layer itself. + let effect = d.node_mut(NodeId(50)).unwrap().appearance.effects.pop().unwrap(); + Arc::make_mut(&mut d.layers[0]).appearance.effects.push(effect); + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the layer's effect moves the file's art: {:?}", r.pixel(50, 80)); +} + +#[test] +fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame() { + // A file that can't be read, in the box (10, 10)–(90, 50), moved 40 points down by a Transform + // effect: crossed at (10, 50)–(90, 90). The view shows the document from y = 55 down, below + // where the box is without the effect; the moved box's diagonal from the top left passes + // (30, 60), the pixel (30, 5). + let mut d = doc_with("outline-cull-1", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let outline = RenderOptions { outline: true, ..preview.clone() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &preview); + let crossed = r.render(&d, 100, 100, view, &outline); + assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed after a frame in Preview"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &outline).pixels, "as a new renderer draws it"); + // In Preview, a layer whose Preview is off draws in outline: the same. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = false; + } + let r = Renderer::new().render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a layer whose Preview is off"); + // And in a sublayer whose Preview is off, in a layer whose Preview is on. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = true; + } + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, sub).unwrap(); + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &outline); + let r = r.render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off"); +} + +#[test] +fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() { + // A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves + // the crossed box 40 points down, to (10, 50)–(90, 90). + let old = doc_with("outline-changed-1", b"bad"); + let mut new = old.clone(); + let params = serde_json::json!({"moveV": 40}); + new.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, 100, 100, Affine::IDENTITY, &opts); + match r.changed(&old, &new, &opts) { + crate::changed::Changed::Area(a) => assert!(a.y1 >= 89.0, "the area reaches the moved box: {a:?}"), + other => panic!("an area, not {other:?}"), + } } #[test] @@ -263,6 +392,82 @@ fn an_enveloped_placed_document_shows_its_file_once_read() { assert!(after == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); } +#[test] +fn outline_mode_warps_an_enveloped_placed_documents_crossed_box() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts).pixels + }; + // An Arc warp of the box (10, 10)–(90, 50), once holding the placed document and once holding + // its crossed box as a plain path. + let envelope = |content: Arc| { + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + Node::new( + NodeId(60), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ) + }; + let mut d = doc_with("outline-envelope-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("a placed document") }; + let crossed = p.crossed_art(&placed); + let l = d.layers[0].id; + d.insert(Some(l), 0, envelope(placed)).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut boxed = d.clone(); + boxed.remove(NodeId(60)).unwrap(); + boxed.insert(Some(l), 0, envelope(Arc::new(crossed))).unwrap(); + let mut r = Renderer::new(); + let warped = outline(&mut r, &d); + assert!(warped == outline(&mut Renderer::new(), &boxed), "the envelope warps the crossed box"); + // With Show Images in Outline Mode the same renderer warps the file's art, and the crossed box + // again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(shown != warped, "the file's art is warped"); + assert!(shown == outline(&mut Renderer::new(), &d), "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d) == warped, "the crossed box again"); +} + +#[test] +fn outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed() { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // A blend of the 40×20 file placed at (5, 5) and at (55, 75), with one step between them: its box + // is (30, 40)–(70, 60), and its diagonal from the top left passes (60, 55). The file's art is a + // rectangle the size of the box. + let mut d = Document::new(100.0, 100.0); + d.images.insert("outline-blend-1".into(), ImageBlob::new("application/json", b"blue".to_vec())); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let ends = vec![ + Arc::new(placed_node(51, "outline-blend-1", 40.0, 20.0, Affine::translate((5.0, 5.0)))), + Arc::new(placed_node(52, "outline-blend-1", 40.0, 20.0, Affine::translate((55.0, 75.0)))), + ]; + let spec = vectorcraft_doc::live::BlendSpec { spacing: vectorcraft_doc::live::BlendSpacing::Steps(1), ..Default::default() }; + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(NodeId(60), NodeKind::Blend { children: ends, spec: Box::new(spec) })).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(inked(&crossed, 60, 55), "the step between the ends is crossed"); + assert!(inked(&crossed, 15, 10) && inked(&crossed, 65, 80), "and so are the ends"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); + d.setup.outline_images = true; + let shown = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(!inked(&shown, 60, 55), "with Show Images in Outline Mode the step is not crossed"); + assert!(inked(&shown, 50, 40), "and its file's art is drawn in outline"); +} + #[test] fn a_placed_document_with_a_drop_shadow_shows_its_file_once_read() { let mut d = doc("shadowed-1"); @@ -433,9 +638,9 @@ fn a_ready_bitmap_draws_again_where_its_file_shows() { let mut r = Renderer::new(); let generation = placed_document::generation(); // The first frame shows the placeholders: the worker waits until it is drawn. - shut_gate(); + let gate = shut_gate(); let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts); - open_gate(); + drop(gate); settle(); let made = placed_document::made_between(generation, placed_document::generation()).expect("known"); let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::>(); @@ -532,9 +737,10 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() { fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() { let _serial = serial(); let d = doc_with("loop-1", b"loop"); - let t = std::time::Instant::now(); + placed_document::reset_deepest(); let r = render(&d, false); - assert!(t.elapsed().as_secs() < 10); + let deepest = placed_document::deepest(); + assert!((2..=vectorcraft_doc::placed_document::MAX_DEPTH).contains(&deepest), "drawn {deepest} levels deep"); assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]); // On screen too. render(&d, true); diff --git a/crates/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 e3dc1ad1e4..02eb4e2202 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -70,7 +70,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. @@ -107,6 +107,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, @@ -1154,7 +1157,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); @@ -1496,7 +1501,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 { @@ -1536,7 +1541,7 @@ impl DirectSelectionTool { // A completed click climbs the group; a drag moves only the selected art. self.click_group = Some(target); } - 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 { @@ -1574,7 +1579,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 = in_selection(cx, 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)); @@ -1588,7 +1593,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 } }; @@ -1606,7 +1611,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}))]; @@ -1634,7 +1639,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![]; @@ -1690,7 +1695,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); } @@ -1799,12 +1804,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 { @@ -1821,7 +1833,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))); @@ -1830,7 +1842,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 1b03ad81d0..b4689642fd 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2312,6 +2312,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] @@ -3023,7 +3067,7 @@ fn select_behind_is_measured_once_for_a_point() { let mut picked = Selection::default(); picked.add(id); let memo = crate::select::PreviewMemo::default(); - let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, behind_armed: true, ..cx(&d, &picked, &p) }; let at = Point::new(150.0, 150.0); let before = MEASURED_PARTS.get(); assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index f93bf3e699..f4c1ecf23b 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -503,6 +503,15 @@ fn dist_seg(p: Point, a: Point, b: Point) -> f64 { p.distance(a + ab * t) } +#[cfg(test)] +thread_local! { + /// The points [`simplify`] has measured against a chord on this thread. + static FLAT_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The anchors [`simplify`] has moved on this thread: each anchor copied into the result, or + /// shifted to close the gap a removed one leaves, counts as one. + static ANCHOR_MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Remove anchors lying flat between their neighbours (all control points within `tol` of the chord). fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { if tol <= 0.0 { @@ -516,6 +525,8 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let mut out: Vec = Vec::with_capacity(n); let mut src = src.into_iter().peekable(); out.extend(src.next()); + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + out.len())); let last = if sp.closed { n } else { n.saturating_sub(1) }; let mut i = 1; while let Some(k) = src.next() { @@ -529,10 +540,16 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let flat = i < last && left >= min && region.contains(k.p) - && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| dist_seg(*q, pa.p, pb.p) <= tol) + && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| { + #[cfg(test)] + FLAT_CHECKS.with(|n| n.set(n.get() + 1)); + dist_seg(*q, pa.p, pb.p) <= tol + }) && (k.p - pa.p).dot(pb.p - k.p) > 0.0; i += 1; if !flat { + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + 1)); out.push(k); continue; } @@ -924,12 +941,17 @@ mod tests { #[test] fn simplify_drops_flat_anchors_and_keeps_the_ends() { - let pts: Vec = (0..200_000).map(|i| Point::new(i as f64, 0.0)).collect(); + let pts: Vec = (0..20_000).map(|i| Point::new(i as f64, 0.0)).collect(); let mut open = SubPath::polyline(&pts, false); - let start = std::time::Instant::now(); + FLAT_CHECKS.with(|n| n.set(0)); + ANCHOR_MOVES.with(|m| m.set(0)); simplify(&mut open, 0.5, Rect::new(-1.0, -1.0, 1e6, 1.0)); - assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); - assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[199_999]]); + // Each anchor is measured once against the chord between its kept neighbors (its point, + // its handles and theirs), and moved at most once. + let (checks, moves) = (FLAT_CHECKS.with(|n| n.get()), ANCHOR_MOVES.with(|m| m.get())); + assert!(checks <= 5 * pts.len(), "{checks} checks for {} anchors", pts.len()); + assert!(moves <= pts.len(), "{moves} moves for {} anchors", pts.len()); + assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[19_999]]); // A closed square with a flat midpoint on each side keeps its four corners. let ring = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0), (0.0, 5.0)]; let mut closed = SubPath::polyline(&ring.map(|(x, y)| Point::new(x, y)), true); diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index d6d4896526..b2cbd22c03 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -520,7 +520,7 @@ fn scissors_shows_paths_alignment_and_configured_anchor_snaps() { } /// A cached snap is for the same raw position, document state and drawing options only. A press -/// gathers fresh targets, even when a previous hover's document state is reused by a caller. +/// gathers fresh targets when the document's revision moved since the hover. #[test] fn scissors_cursor_and_press_use_current_snaps() { let (d, rect) = doc_with_rect(); @@ -564,7 +564,7 @@ fn scissors_cursor_and_press_use_current_snaps() { let before = cx(&crossing, &selected, &paint); let mut tool = AnchorTool::new("scissors"); tool.pointer(&before, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)); - let after = cx(&d, &selected, &paint); + let after = ToolContext { revision: (0, 1), ..cx(&d, &selected, &paint) }; let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(152.0, 100.0)) < 1e-6, "{actions:?}"); } diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 0a48b35001..20caa7de19 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -325,9 +325,10 @@ pub fn square(d: Vec2) -> Vec2 { /// too, so they all snap alike, and shows its [`Self::guides`]. /// /// The targets ([`Targets::for_drawing`], the art in the window) are gathered once per document -/// state: hovering gathers them again only after the document, the selection, what is left out, -/// the window or the snapping options changed; a press always gathers them afresh, and the drag -/// it starts keeps them, the document then showing the drag's own previews. +/// state: hovering and pressing gather them again only after the document, the selection, what is +/// left out, the window or the snapping options changed, so a press keeps the targets the hover +/// before it gathered. The drag a press starts keeps them, the document then showing the drag's +/// own previews. /// /// The Measure and Measure & Inspect tools keep one too, for the ends of a drag only. They do not /// ask it while hovering. [`Self::measure`] gathers [`Targets::for_measure`] instead, and a press @@ -415,17 +416,14 @@ impl DrawSnap { /// Snap the pointer hovering at `p` (the art but `exclude` as targets, the anchors of /// `exclude` still pulling), reusing the targets while nothing they depend on changed. pub fn hover(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - let key = SnapKey::of(cx, exclude); - if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { - self.gather(cx, key); - } + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } - /// Snap the point pressed at `p`, the targets gathered afresh: the drag that follows keeps - /// them ([`Self::drag`]). + /// Snap the point pressed at `p`, reusing the targets the last hover or press gathered while + /// nothing they depend on changed: the drag that follows keeps them ([`Self::drag`]). pub fn press(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - self.gather(cx, SnapKey::of(cx, exclude)); + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } @@ -544,6 +542,15 @@ impl DrawSnap { }; } + /// Gather the targets for the art but `exclude` unless the last hover or press gathered them + /// for the same [`SnapKey`]. + fn gather_unless_current(&mut self, cx: &ToolContext, exclude: &[NodeId]) { + let key = SnapKey::of(cx, exclude); + if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { + self.gather(cx, key); + } + } + fn gather(&mut self, cx: &ToolContext, key: SnapKey) { let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph)); self.targets = Some((Some(key), snap)); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 0406ea5f77..4b6e333d80 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -682,8 +682,8 @@ fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() { assert_eq!(snap.press(&off, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 315.0)); } -/// A drawing tool's snapper reuses its targets while hovering over the same document state, and -/// gathers them again when it changes, and on every press. +/// A drawing tool's snapper reuses its targets while hovering and pressing over the same document +/// state, and gathers them again when it changes. #[test] fn draw_snap_gathers_once_per_document_state() { let (d, _) = doc_with_rect(); @@ -694,17 +694,19 @@ fn draw_snap_gathers_once_per_document_state() { let c = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); assert_eq!(labels(snap.guides()), ["anchor"]); - // The same revision: the targets are the ones gathered (the document isn't read again). + // The same revision: the targets are the ones gathered (the document isn't read again), for + // a hover and for the press after it. let c = ToolContext { revision: (1, 1), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); - // A new revision, or a press, reads it. + assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); + // A new revision reads it, for a hover and for a press. let c = ToolContext { revision: (1, 2), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), at); assert!(snap.guides().is_empty()); - let c = ToolContext { revision: (1, 2), ..cx(&d, &s, &p) }; + let c = ToolContext { revision: (1, 3), ..cx(&d, &s, &p) }; assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); // The drag keeps what the press gathered, though the document now shows its preview. - let c = ToolContext { revision: (1, 3), ..cx(&empty, &s, &p) }; + let c = ToolContext { revision: (1, 4), ..cx(&empty, &s, &p) }; assert_eq!(snap.drag(&c, at, None), Point::new(200.0, 200.0)); snap.clear(); assert!(snap.guides().is_empty()); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ec2b83f1a6..449dad62d8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -668,6 +668,7 @@ pub(crate) mod testutil { double_click_isolate: true, double_click_adds_anchor: false, select_behind: true, + behind_armed: false, highlight_anchors: true, snap_tolerance: 2.0, handles_multiple: true, diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index dd26fa28f0..5871d07126 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -171,7 +171,7 @@ mod tests { (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. - (&["place"], &["count", "current", "name", "width", "height", "names"]), + (&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); // Tools that `create` makes and the catalog doesn't list. diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 813ec99429..84f6ee1bad 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -9,9 +9,18 @@ use vectorcraft_geom::{Point, Rect}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +/// Private cursor metadata: the original queue entry for a placement request. The frontend +/// consumes it before opening import options; the engine removes it before direct placement. +pub const SOURCE_INDEX: &str = "__placeSourceIndex"; + +/// Whether a cursor placement was a click under the pointer tolerance, rather than a drag. +pub const CLICK: &str = "__placeCursorClick"; + /// One loaded file. #[derive(Clone, Debug, PartialEq)] struct Entry { + /// Its position in the original load, retained when other entries are discarded. + source_index: usize, /// `file.place` params (the file and its options). params: Value, name: String, @@ -93,9 +102,12 @@ impl Tool for PlaceTool { let Some((a, _)) = self.drag.take() else { return vec![] }; let (Some(r), Some(e)) = (self.target(a, ev.pos, cx.tol(3.0)), self.entry()) else { return vec![] }; let mut p = e.params.clone(); + p[SOURCE_INDEX] = json!(e.source_index); + let clicked = (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0); + p[CLICK] = json!(clicked); p["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); // A Shift-click (not a drag) asks for the file's import options before placing it. - if ev.mods.shift && (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0) { + if ev.mods.shift && clicked { p["showImportOptions"] = json!(true); } let mut acts = vec![Action::Exec("file.place".into(), p)]; @@ -141,12 +153,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), "current": self.current, + "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), "width": e.map(|e| e.width), "height": e.map(|e| e.height), @@ -163,8 +176,10 @@ impl Tool for PlaceTool { .as_array() .into_iter() .flatten() - .filter_map(|e| { + .enumerate() + .filter_map(|(source_index, e)| { Some(Entry { + source_index, params: e.get("params").filter(|p| p.is_object())?.clone(), name: e["name"].as_str().unwrap_or_default().to_string(), width: e["width"].as_f64().filter(|v| v.is_finite())?, @@ -277,14 +292,26 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0)); - assert_eq!(acts, vec![Action::Exec("file.place".into(), json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0]}))]); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0]}) + )] + ); // A drag up and to the left grows the box from the press point, aspect kept. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0)); let c_marquee_only = ToolContext { measurement_labels: false, ..c }; assert_eq!(t.overlays(&c_marquee_only), vec![Overlay::Marquee(Rect::new(20.0, 60.0, 100.0, 100.0))]); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); assert_eq!(t.options()["count"], 1); // Placing the last file returns to the previous tool. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); @@ -302,18 +329,30 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0).with_mods(shift)); - let asked = json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); + let asked = json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); assert_eq!(acts, vec![Action::Exec("file.place".into(), asked)]); assert_eq!(t.options()["names"], json!(["f1.png", "f2.png"]), "the cursor goes on to the next file"); // A Shift-drag places at the dragged size, as a drag does. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0).with_mods(shift)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0).with_mods(shift)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); // Shift released before the button: a plain click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + ) + ); assert_eq!(acts.last(), Some(&Action::SwitchTool("pen".into()))); // An empty cursor places nothing on a Shift-click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); @@ -359,4 +398,29 @@ mod tests { t.key(&c, ToolKey::Escape, Mods::default()); assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + + #[test] + fn source_indices_survive_removal_in_cursor_requests() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = loaded(3); + t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(t.options()["sourceIndex"], 1); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!((t.options()["current"].clone(), t.options()["sourceIndex"].clone()), (json!(1), json!(2))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + )] + ); + assert_eq!(t.options()["sourceIndex"], 0); + assert!(t.check_option("sourceIndex", &json!(0)).is_err(), "the source identity is read only"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(t.options()["sourceIndex"], Value::Null); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cb02554785..f921b19fea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -41,7 +41,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, leaves_at, marquee_in_view, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -520,8 +520,6 @@ struct Measured { painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, - /// [`selection_holders`]. - holders: Option>>, /// [`selects_behind_at`]'s last answer, with the point and settings it was for. behind: Option<(BehindKey, bool)>, } @@ -598,7 +596,6 @@ impl PreviewMemo { by_object: HashMap::new(), painted: [None, None], part_boxes: None, - holders: None, behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { @@ -817,7 +814,7 @@ pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { } /// [`hold_point`]'s point of the path hit, None when the press holds no point of it. -fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { +pub(crate) fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } @@ -1215,9 +1212,11 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } - // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). + // 3. Objects: once armed, Cmd/Ctrl-click selects the one under the selected one + // (cycling). if m.cmd && cx.select_behind + && cx.behind_armed && let Some(behind) = object_behind(cx, p) { self.state = @@ -1569,13 +1568,14 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an -/// object under the pointer selected or holding selected art (a group with a selected member), +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and +/// armed by an earlier Cmd/Ctrl press ([`ToolContext::behind_armed`]), and is an object under the +/// pointer ([`leaves_at`]) selected or inside a selected object (a member of a selected group), /// with another object under the pointer too, away from the anchors, handles, mesh points and /// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the /// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { - if !cx.select_behind { + if !cx.select_behind || !cx.behind_armed { return false; } let tol = cx.pick_tol(); @@ -1599,8 +1599,8 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) && { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - stack.len() > 1 && holds_selection(cx, &stack).is_some() + let stack = under_pointer(cx, p); + stack.len() > 1 && lowest_selected(&stack).is_some() } && !crate::direct::over_selected_part(cx, p); if let Some(memo) = cx.preview_memo @@ -1616,25 +1616,25 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { behind } -/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is -/// selected or holds selected art, such as a group with a member picked by Direct Selection or -/// Group Selection. -fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { - let holders = selection_holders(cx); - stack.iter().rposition(|id| holders.contains(id)) +/// The objects under `p` that Select Behind steps through, topmost first: for each object a Direct +/// Selection click picks there ([`leaves_at`]; in a compound path, the path under the pointer), the +/// object and whether it is selected or inside a selected object. +fn under_pointer(cx: &ToolContext, p: Point) -> Vec<(NodeId, bool)> { + let tol = cx.pick_tol(); + leaves_at(cx.doc, p, cx.selection_hit_options()) + .into_iter() + .map(|h| { + let part = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)); + let picked = h.ancestry.iter().copied().chain(std::iter::once(h.leaf)).chain(part).any(|id| cx.selection.contains(id)); + (part.unwrap_or(h.leaf), picked) + }) + .collect() } -/// The selected objects and every object that holds one (their groups and layers), kept in the -/// session's [`PreviewMemo`] while the document and the selection stay as they are. -fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { - remembered( - cx, - |m| &mut m.holders, - || { - let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); - std::sync::Arc::new(set) - }, - ) +/// The index in `stack` ([`under_pointer`]) of the lowest object that is selected or inside a +/// selected object. +fn lowest_selected(stack: &[(NodeId, bool)]) -> Option { + stack.iter().rposition(|(_, picked)| *picked) } /// The selected object `id` and the objects holding it, outermost first, from the object a click @@ -1660,13 +1660,13 @@ fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { holder_chain(cx, id).first().copied().unwrap_or(id) } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is -/// selected or holds selected art, back to the topmost after the bottom one; the topmost when -/// none is. +/// Select Behind: of the objects under `p` ([`under_pointer`], topmost first, members of groups +/// one by one), the one below the lowest one that is selected or inside a selected object, back to +/// the topmost after the bottom one; the topmost when none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); - stack.get(next).or(stack.first()).copied() + let stack = under_pointer(cx, p); + let next = lowest_selected(&stack).map_or(0, |i| i + 1); + stack.get(next).or(stack.first()).map(|(id, _)| *id) } /// The selected object a press on `h` lands on: `top` when it is selected, else the outermost diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 134b9b6069..6ef02bfd11 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -204,6 +204,8 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::()) }; s.spend(cost)?; + #[cfg(test)] + VISITED.with(|v| v.set(v.get() + s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::())); let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; if let Some(live) = drawn_live(doc, &h.ancestry) { if let Some(c) = live_color_at(s, levels, live, p) { @@ -270,6 +272,9 @@ fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: thread_local! { /// The blends and envelopes [`live_color_at`] has evaluated on this thread. static EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects the hit tests of [`color_under`] may have visited on this thread: every object + /// of the document hit, and the symbols' art. + static VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol @@ -1584,11 +1589,23 @@ mod tests { d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); } let (s, p) = (Selection::default(), paint()); - let start = std::time::Instant::now(); + let cx = cx(&d, &s, &p); + let opts = sample_options(&cx); + let symbol_nodes = d.symbols.iter().map(|s| s.art.count()).sum(); for at in [Point::new(150.5, 150.5), Point::new(350.5, 350.5), Point::new(350.5, 50.5)] { - assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + assert_eq!(sample_color_at(&cx, at), None, "{at:?}"); + // Sampled on this thread, so the count is this sample's. Each hit test counts the + // objects it may visit against the limit first, except the first one in the document, + // which a click makes anyway. + VISITED.with(|v| v.set(0)); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false, patterns: 0 }; + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, &d, &mut levels, at, opts); + assert!(c.is_none() || s.exhausted, "{at:?}"); + let allowed = MAX_WORK + symbol_nodes + d.layers.iter().map(|l| l.count()).sum::(); + let visited = VISITED.with(|v| v.get()); + assert!(visited <= allowed, "{at:?}: hit tests may have visited {visited} objects, {allowed} allowed"); } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); } /// Each hit test in a tile's art may measure the art of every symbol, so it counts the symbols' diff --git a/crates/trace/src/logo/pipeline.rs b/crates/trace/src/logo/pipeline.rs index 16bb1b3b08..4e605393cf 100644 --- a/crates/trace/src/logo/pipeline.rs +++ b/crates/trace/src/logo/pipeline.rs @@ -406,7 +406,14 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul // Every entry is checked, but only the first few distinct colours are kept. let c = parse_hex(s).ok_or_else(|| TraceError::BadPalette(s.clone()))?; let white = own_white(params) && c.iter().all(|&v| v >= WHITE_MIN); - if palette.len() < MAX_COLOURS && !white && !palette.iter().any(|&q| distance(q, c) < SAME_COLOUR) { + if palette.len() < MAX_COLOURS + && !white + && !palette.iter().any(|&q| { + #[cfg(test)] + NAMED_COMPARISONS.with(|n| n.set(n.get() + 1)); + distance(q, c) < SAME_COLOUR + }) + { palette.push(c); } } @@ -418,6 +425,12 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul Ok((palette, tones)) } +#[cfg(test)] +thread_local! { + /// The named colors [`choose_palette`] has compared with the ones it kept, on this thread. + pub(crate) static NAMED_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Trace a flat-colour logo. pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result { let (w0, h0) = (img.width as usize, img.height as usize); diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 8d493d3a56..00b05b350c 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -632,9 +632,12 @@ fn a_large_odd_sized_image_never_overshoots_its_edges() { fn a_hostile_palette_is_bounded_and_near_duplicates_merge() { let img = render(64, 64, 0.7, |x, y| ((x - 32.0).hypot(y - 32.0) <= 20.0).then_some(RED)); let many: Vec = std::iter::once("#d22832".to_string()).chain((1..200_000u32).map(|i| format!("#{:06x}", i * 37 % 0xfffff0))).collect(); - let started = std::time::Instant::now(); + let named = many.len(); + super::pipeline::NAMED_COMPARISONS.with(|n| n.set(0)); let res = trace_within(&img, &TraceParams { logo_colors: many, ..logo_params() }, 100_000); - assert!(started.elapsed().as_secs() < 20, "palette handling took {:?}", started.elapsed()); + // Each named color is compared with the ten or fewer kept so far, not with every one before it. + let comparisons = super::pipeline::NAMED_COMPARISONS.with(|n| n.get()); + assert!(comparisons <= 10 * named, "{comparisons} comparisons for {named} named colors"); if let Ok(r) = res { assert!(r.palette.len() <= 11); } diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a115cd3ce3..14761689de 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -17,6 +17,8 @@ pub(crate) use denoise::{Source, denoise_nearest}; pub use palette::FULL_TONE_MAX; use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library}; #[cfg(test)] +pub(crate) use palette::{LIBRARY_COMPARISONS, SWATCH_LOOKUPS}; +#[cfg(test)] pub(crate) use rare::kept_rare; use rare::{rare_colours, refine_around}; diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 63c8fe9a06..7e0a14a787 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -121,6 +121,8 @@ const LIBRARY_CHROMA_WEIGHT: f64 = 3.0; /// hue and chroma counted [`LIBRARY_CHROMA_WEIGHT`] times: a neutral or muted tone takes a neutral /// library color of another lightness rather than a saturated one of its own lightness. pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { + #[cfg(test)] + LIBRARY_COMPARISONS.with(|n| n.set(n.get() + labs.len())); let mut best = (f64::INFINITY, 0); for (i, m) in labs.iter().enumerate() { let d = (m[0] - c[0]).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[1] - c[1])).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[2] - c[2])).powi(2); @@ -131,6 +133,15 @@ pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { best.1 } +#[cfg(test)] +thread_local! { + /// The swatch colors [`nearest_library`] has compared a color with, on this thread. + pub(crate) static LIBRARY_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The lookups [`library_colors`] has made to tell whether a swatch's color was seen before, + /// on this thread: one per set lookup, or one per earlier color a scan compares it with. + pub(crate) static SWATCH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { colors.iter().map(|c| oklab(*c)).collect() } @@ -252,7 +263,15 @@ fn clean_levels(used: &[Used], min_share: f64) -> Option { fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> { // Each colour once, in their order: looked up in a set, not in the colours kept so far. let mut seen = std::collections::HashSet::new(); - let all: Vec<[f64; 3]> = swatches.iter().filter(|s| seen.insert(**s)).map(|s| s.map(f64::from)).collect(); + let all: Vec<[f64; 3]> = swatches + .iter() + .filter(|s| { + #[cfg(test)] + SWATCH_LOOKUPS.with(|n| n.set(n.get() + 1)); + seen.insert(**s) + }) + .map(|s| s.map(f64::from)) + .collect(); let mut weight = vec![0.0; all.len()]; let all_labs = labs(&all); for (_, c, n) in used { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 694892a8a6..3fd5c2000b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -821,9 +821,17 @@ fn a_library_of_many_repeated_swatches_is_read_once_per_color() { }) .collect(); let params = TraceParams { mode: Mode::Color, palette: Palette::DocumentLibrary, swatches, colors: 2, ..TraceParams::default() }; - let start = std::time::Instant::now(); + let distinct = 50_000; + let count = params.swatches.len(); + quantize::LIBRARY_COMPARISONS.with(|n| n.set(0)); + quantize::SWATCH_LOOKUPS.with(|n| n.set(0)); let q = quantize(&img, ¶ms); - assert!(start.elapsed() < std::time::Duration::from_secs(30), "{:?}", start.elapsed()); + // Each swatch is looked up once to drop the repeats. The two colors of the picture are each + // compared with every distinct swatch once, and the image's few bins with the two swatches kept. + let lookups = quantize::SWATCH_LOOKUPS.with(|n| n.get()); + assert!(lookups > 0 && lookups <= count, "{lookups} lookups for {count} swatches"); + let comparisons = quantize::LIBRARY_COMPARISONS.with(|n| n.get()); + assert!(comparisons > 0 && comparisons <= 2 * distinct + 1_000, "{comparisons} comparisons for {distinct} distinct swatches"); assert_eq!(q.labels.len(), 2); } diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 52b8130b1b..a26f5f7a28 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use craft::menu::Node; use craft::ui::canvas::ViewCommands; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -221,16 +222,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |_| dialog(GRID, grid_rows(lengths))), - REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |_| dialog(REPLACE, replace_rows())), + GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), + REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); - dialog(OPACITY, opacity_rows()).ok_enabled(min <= max) + dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) }), - SORT => super::dialogs::open(app, &SORT_SPEC, fields, |_| dialog(SORT, sort_rows())), + SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); - dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()) + dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) }), }; Some(opened) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index ad24ac5a37..420bfdb01d 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::ZOOM; use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::{VectorcraftApp, menus}; /// An app with a window, where its dialogs open, and two rectangles without a stroke, both selected. @@ -29,6 +30,85 @@ fn click(app: &mut VectorcraftApp, label: &str) { menus::invoke(app, &id, p); } +/// Replace a numeric field's text and commit by moving focus, without confirming the dialog. +fn type_number(panel: &mut Harness, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +#[test] +fn real_grid_edits_reach_the_preview_and_confirmed_geometry() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Arrange in Grid…"); + type_number(&mut panel, "Columns", "1"); + type_number(&mut panel, "V Spacing", "7"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.int("columns")), Some(1)); + let preview = { + let app = panel.app(); + (bounds(&app, a), bounds(&app, b)) + }; + assert!((preview.0.center().x - preview.1.center().x).abs() < 1e-6); + assert!((preview.1.y0 - preview.0.y1 - 7.0).abs() < 1e-6); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), preview); + assert!(!app.any_dialog_open()); +} + +#[test] +fn real_size_keyboard_edits_keep_unticked_sides_unchanged() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Set Size of Each…"); + panel.frame(); + panel.focus("Height"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + // Width's number follows its checkbox in keyboard order; the number has no separate caption. + panel.focus("Width"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("30"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| (f.number("width"), f.bool("heightOn"))), (Some(30.0), Some(false))); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let (first, second) = (bounds(&app, a), bounds(&app, b)); + assert_eq!((first.width(), first.height()), (30.0, 10.0)); + assert_eq!((second.width(), second.height()), (30.0, 40.0)); +} + +#[test] +fn real_opacity_edits_drive_validation_confirmation_and_cancel() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "80"); + type_number(&mut panel, "Maximum", "20"); + assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation"); + type_number(&mut panel, "Maximum", "80"); + assert!(panel.enabled("OK")); + panel.click("OK"); + panel.frame(); + let opacity = |panel: &Harness, id| panel.app().session.doc().unwrap().doc.node(id).unwrap().opacity; + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert!((opacity(&panel, a) - 0.25).abs() < 1e-6); + panel.click("Cancel"); + panel.frame(); + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/addons/color/legend.rs b/crates/ui-egui/src/addons/color/legend.rs index 9f4d6a8729..31fa3a5011 100644 --- a/crates/ui-egui/src/addons/color/legend.rs +++ b/crates/ui-egui/src/addons/color/legend.rs @@ -3,6 +3,7 @@ //! labels show, and whether only the swatches selected in the Swatches panel are drawn. It //! previews on the canvas and runs `addon.color.swatchLegend` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -75,7 +76,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if fields.list("names").is_some_and(|names| !names.is_empty()) { rows.push(Param::new("selectedOnly", tl!("Selected Swatches Only"), ParamKind::bool(false))); } - ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/color/legend/tests.rs b/crates/ui-egui/src/addons/color/legend/tests.rs index c07d71c19f..df4f88dcd9 100644 --- a/crates/ui-egui/src/addons/color/legend/tests.rs +++ b/crates/ui-egui/src/addons/color/legend/tests.rs @@ -1,6 +1,90 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use vectorcraft_doc::NodeKind; + +fn assert_edited_legend(app: &VectorcraftApp) { + let state = app.session.active().unwrap(); + let group = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(group.name.as_deref(), Some("Swatch Legend")); + let children = group.children().unwrap(); + let chips: Vec<_> = children.iter().filter(|node| matches!(node.kind, NodeKind::Path { .. })).collect(); + let labels: Vec<_> = children + .iter() + .filter_map(|node| match &node.kind { + NodeKind::Text(text) => Some(text.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(chips.len(), 3, "only the three selected swatches are drawn"); + assert_eq!(labels.len(), 3); + let bounds = |index: usize| chips[index].geometric_bounds().unwrap(); + assert!((bounds(0).width() - 40.0).abs() < 1e-6, "the typed chip size reaches the legend"); + assert!((bounds(1).x0 - bounds(0).x0 - 50.0).abs() < 1e-6, "the typed gap separates columns"); + assert!((bounds(2).x0 - bounds(0).x0).abs() < 1e-6 && (bounds(2).y0 - bounds(0).y0 - 50.0).abs() < 1e-6, "two columns wrap the third chip"); + for label in labels { + assert!( + label.lines().any(|line| line.starts_with('#')) && label.lines().any(|line| line.starts_with("C=")), + "the selected value formats reach the label: {label}" + ); + assert!(["Ink", "Paper", "Signal"].contains(&label.lines().next().unwrap())); + } +} + +/// Real controls change the preview's layout and labels; Cancel restores the drawing, while +/// OK with Preview switched off applies the same hosted fields in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_legend_preview_ok_and_cancel() { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + for (name, color) in [("Ink", "#123456"), ("Paper", "#f8f4e8"), ("Signal", "#cc2211")] { + app.run("swatch.new", json!({"name": name, "color": color})).unwrap(); + } + app.ui.swatches_panel.set_swatches(vec!["Ink".into(), "Paper".into(), "Signal".into()]); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on"); + assert!(panel.app().session.in_interaction(), "the initial legend is previewed"); + if commit { + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!panel.app().session.in_interaction()); + } + panel.click_role("Selected Swatches Only", Role::CHECK_BOX); + panel.click_role("HEX", Role::CHECK_BOX); + panel.click_role("CMYK", Role::CHECK_BOX); + for (label, input) in [("Columns", "2"), ("Size", "40 pt"), ("Gap", "10 pt")] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + /// The names of the swatches chosen in the Swatches panel are sent only with Selected Swatches Only, and only when /// there are some; the values go only for the ticked boxes. #[test] diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs index 6db4ec9332..cc393f80a0 100644 --- a/crates/ui-egui/src/addons/color/nearest.rs +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -132,10 +132,7 @@ impl StackDialog for NearestDialog { /// The dialog's rows: the library, Fill and Stroke, then what the query found (or what to do first). fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry], selected: bool, found: Option<&(QueryKey, Result)>) { Field::new(label(tl!("Library:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Library:")), Bind::given(fields.library.clone()), libraries).show(ui).value().cloned(); - if let Some(library) = picked { - fields.library = library; - } + Select::new(label(tl!("Library:")), Bind::bound(&mut fields.library), libraries).show(ui); }); Row::new().show(ui, |ui, _| { Checkbox::new(Bind::bound(&mut fields.fill)).label(label(tl!("Fill"))).show(ui); @@ -286,4 +283,41 @@ mod tests { assert!(p.shows(name), "{name} is drawn"); } } + + /// A highlighted library previews its matches; Escape restores the library and results that + /// were current before the popup opened, while Enter keeps a deliberate choice. + #[test] + fn cancelling_a_library_popup_restores_the_original_library_and_matches() { + use egui::{Key, Modifiers}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), COMMAND, serde_json::Value::Null); + panel.frame(); + panel.frame(); + let original = listed(&panel.app()).unwrap(); + let library = |panel: &crate::tests::panel_harness::Panel| host(&panel.app(), |h| h.get::().unwrap().fields.library.clone()); + assert_eq!(library(&panel), "document"); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = library(&panel); + assert_ne!(proposed, "document", "the open popup previews another enabled library"); + assert_ne!(listed(&panel.app()), Some(original.clone()), "the query follows the highlighted library"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), "document"); + assert_eq!(listed(&panel.app()), Some(original)); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), proposed, "a deliberate choice is kept"); + assert!(host(&panel.app(), |h| h.is_open::()), "choosing a library does not apply and close the dialog"); + } } diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index fbdb25d1f3..7fde5f2f4b 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -340,8 +340,9 @@ impl View { Some((f, ms)) } - /// What the window draws for `doc` at `revision` with `set`: its blanks, the fold and the print. - fn scene(&mut self, ui: &Ui, doc: &Arc, uid: u64, revision: u64, set: &Settings) -> Scene { + /// What the window draws for `doc` at `revision` with `set` at `now` (seconds on the app's + /// clock): its blanks, the fold and the print. + fn scene(&mut self, ui: &Ui, doc: &Arc, uid: u64, revision: u64, set: &Settings, now: f64) -> Scene { let (blanks, errors) = self.blanks(uid, revision, doc); let base = set.base.map(|[x, y]| Point::new(x, y)); let picked = pick(&blanks, base).or_else(|| pick(&blanks, None)); @@ -349,13 +350,13 @@ impl View { let blank = blanks.get(b)?; let key = (uid, revision, b, panel, set.amount.to_bits()); let (folded, fold_ms) = self.fold(key, blank, panel, set.amount)?; - let print = self.print_of(ui, doc, key, blank, set.show_fold_lines); + let print = self.print_of(ui, doc, key, blank, set.show_fold_lines, now); Some(Folding { doc: doc.clone(), blanks: blanks.clone(), blank: b, folded, key, fold_ms, print }) }); Scene { blanks: blanks.len(), errors, drawn } } - /// The print to draw for the fold `key` of `blank`, brought up to date first. + /// The print to draw for the fold `key` of `blank`, brought up to date first at `now`. fn print_of( &mut self, ui: &Ui, @@ -363,6 +364,7 @@ impl View { key: FoldKey, blank: &Blank, fold_lines: bool, + now: f64, ) -> Option<(PrintKey, Arc)> { let region = print_region(blank)?; let (width, height, scale) = print_size(region); @@ -374,13 +376,14 @@ impl View { width, height, }; - self.update_print(ui, doc, pkey, region, scale); + self.update_print(ui, doc, pkey, region, scale, now); self.print_for(&pkey) } /// Take in the prints that finished, then bring the print up to `key`: queued on the host's - /// jobs, and not before the document has settled unless there is no print of it yet. - fn update_print(&mut self, ui: &Ui, doc: &Arc, key: PrintKey, region: DRect, scale: f64) { + /// jobs, and not before the document has settled by `now` (seconds on the app's clock) unless + /// there is no print of it yet. + fn update_print(&mut self, ui: &Ui, doc: &Arc, key: PrintKey, region: DRect, scale: f64, now: f64) { let queue = self.prints.get_or_insert_with(|| print_queue(ui)); let inline = QueueOptions::default_lanes() == 0; if inline { @@ -403,7 +406,7 @@ impl View { return; } let have = shown.is_some_and(|k| k.uid == key.uid); - if have && !self.settle.settled(ui.ctx(), key.uid, key.revision, monotonic_ms() / 1000.0) { + if have && !self.settle.settled(ui.ctx(), key.uid, key.revision, now) { return; } let opts = vectorcraft_render::RenderOptions { @@ -626,6 +629,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); let mut set = app.ui.fold_preview.clone().clamped(); let words = Env::of(ui).words::(); + let now = app.now(); let view = &mut app.addon_panels.fold_view; let mut drawn = None; Stack::new().fill().show(ui, |ui, _| { @@ -635,7 +639,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .step(1.0) .unit_kind(UnitKind::Degrees) .show(ui); - let scene = view.scene(ui, &doc, uid, revision, &set); + let scene = view.scene(ui, &doc, uid, revision, &set, now); let out = FoldView::new(words.image.clone(), set.clone(), scene.drawn.clone(), view.shown.clone()).sizing(Sizing::Fill).show(ui); set = out.set; drawn = out.drawn; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 4eca13035a..63f7bcc3a3 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -12,9 +12,7 @@ use vectorcraft_three_d::fold::raster::{Image, MAX_PIXELS, MAX_SIDE}; use super::{PrintKey, Settings, Shown, View, inside_color, show, status}; use crate::VectorcraftApp; - -/// How long a test waits for the print to render. -const PRINT_WAIT: Duration = Duration::from_secs(30); +use crate::thumb_worker::SETTLE_SECS; /// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each /// side) and a red square printed on the base, nothing selected → (app, the red square's id). @@ -37,6 +35,7 @@ fn app() -> (VectorcraftApp, u64) { app.run("paint.setStroke", json!({ "none": true })).unwrap(); app.run("object.arrange.sendToBack", json!({})).unwrap(); app.run("select.none", json!({})).unwrap(); + app.now_override = Some(0.0); (app, red) } @@ -74,11 +73,12 @@ impl Window { /// Frames until the print of the document as it is has been rendered and drawn. fn settle(&mut self, app: &mut VectorcraftApp) -> Shown { for _ in 0..SETTLE_FRAMES { + tick(app); self.frame(app); if print_ready(app) { break; } - wait_for_print(app); + finish_print(app); } assert!(print_ready(app), "the print renders"); for _ in 0..3 { @@ -88,9 +88,18 @@ impl Window { } } -/// Most frames a test runs while it waits for the print: the window waits for the document to -/// settle (by the real clock) before it renders a print of a changed document. -const SETTLE_FRAMES: usize = 200; +/// Most frames a test runs while it waits for the print: one notes the change, the next finds the +/// document settled and queues the print, and the one after that takes the finished print in. +const SETTLE_FRAMES: usize = 8; + +/// How far [`tick`] moves the app's clock: more than [`SETTLE_SECS`], and exact in binary. +const TICK_SECS: f64 = 1.0; + +/// Moves the app's clock on by [`TICK_SECS`], so the next frame finds a document that changed +/// before it settled. +fn tick(app: &mut VectorcraftApp) { + app.now_override = Some(app.now() + TICK_SECS); +} /// Whether the print shown is the one of the document and Show Fold Lines setting as they are. fn print_ready(app: &VectorcraftApp) -> bool { @@ -99,12 +108,11 @@ fn print_ready(app: &VectorcraftApp) -> bool { view.pending.is_none() && view.print.as_ref().map(|(k, _)| (Some(k.revision), k.fold_lines)) == Some(wanted) } -/// Lets a queued print finish, and gives the settle gate time to pass. -fn wait_for_print(app: &VectorcraftApp) { +/// Waits until the queued print has rendered, so the next frame takes it in. +fn finish_print(app: &VectorcraftApp) { if let Some(queue) = &app.addon_panels.fold_view.prints { - queue.finish(PRINT_WAIT); + assert!(queue.finish(Duration::MAX), "the print queue finishes its work"); } - std::thread::sleep(Duration::from_millis(20)); } /// Draws the window in a 520 × 440 room and settles it. @@ -205,6 +213,30 @@ fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs assert!(same, "no new print without a change"); } +#[test] +fn a_changed_document_is_printed_again_once_it_has_settled_on_the_app_clock() { + let (mut app, _) = app(); + let mut window = Window::new(1.0, vec2(520.0, 440.0)); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + window.settle(&mut app); + let printed = |app: &VectorcraftApp| app.addon_panels.fold_view.print.as_ref().map(|(k, _)| k.revision); + let before = printed(&app); + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + // The frame that sees the change, and a frame before the clock has moved on by the settle time, + // queue no print. + window.frame(&mut app); + app.now_override = Some(app.now() + SETTLE_SECS / 2.0); + window.frame(&mut app); + assert!(app.addon_panels.fold_view.pending.is_none(), "no print is queued while the document settles"); + app.now_override = Some(app.now() + SETTLE_SECS); + window.frame(&mut app); + assert!(app.addon_panels.fold_view.pending.is_some(), "the print is queued once the app's clock passes the settle time"); + finish_print(&app); + window.frame(&mut app); + let after = printed(&app); + assert!(after.is_some() && after != before, "the print is of the changed document: {before:?} then {after:?}"); +} + #[test] fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { let (mut app, _) = app(); @@ -323,11 +355,12 @@ impl Rig { /// Frames until the print of the document as it is has been rendered and drawn. fn settle(&mut self) { for _ in 0..SETTLE_FRAMES { + tick(&mut self.app.borrow_mut()); self.fx.idle(1); if print_ready(&self.app.borrow()) { break; } - wait_for_print(&self.app.borrow()); + finish_print(&self.app.borrow()); } assert!(print_ready(&self.app.borrow()), "the print renders"); self.fx.idle(3); diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index 5e820e5f35..f24542b81d 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,6 +1,7 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners //! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which -//! can also take every other anchor, or only the corners in an angle range). +//! can also take every other anchor, or only the corners in an angle range). Canceling a Radius edit +//! or Corner choice restores its opening tool value; a retired edit supplies no replacement. use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, Sizing, clicked}; @@ -55,12 +56,12 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let radius_field = |ui: &mut Ui| { let field = fields::size_field(ui, tl!("Radius"), Some(radius), lengths).range(0.0..=MAX_RADIUS); - typed(field.show(ui).value()) + typed(field.show(ui).events.landed()) }; if let Some(v) = row(ui, "Radius", "corner-tool-radius", radius_field) { set = Some(json!({ "radius": v })); } - let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied(); + let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).events.landed().copied(); if let Some(k) = row(ui, "Corner", "corner-tool-kind", kind_field) { set = Some(json!({ "kind": k })); } @@ -76,3 +77,81 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_tools::addons::shared_edge; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.setOption", json!({"tool": ID, "values": {"radius": 12.5, "kind": "round"}})).unwrap(); + app.run("tool.setOption", json!({"tool": shared_edge::ID, "values": {"diameter": 14.25, "tolerance": 0.5}})).unwrap(); + app + } + + #[test] + fn canceling_a_corner_kind_popup_restores_the_tools_complete_options() { + let mut panel = Panel::new(app(), section); + let before = panel.app().session.tool_options_of(ID); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = panel.app().session.tool_options_of(ID); + assert_ne!(proposed["kind"], before["kind"], "the choice previews the next corner kind"); + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), before); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), proposed, "Enter accepts the new tool setting"); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "tool settings do not edit the drawing"); + } + + #[test] + fn canceling_an_option_text_edit_restores_options_and_enter_keeps_accepted_edits() { + for (draw, tool, label, key, typed) in [ + (section as fn(&mut VectorcraftApp, &mut Ui), ID, "Radius", "radius", "19.75"), + (super::super::shared_edge::section, shared_edge::ID, "Diameter", "diameter", "28.5"), + (super::super::shared_edge::section, shared_edge::ID, "Coincidence", "tolerance", "0.75"), + ] { + for cancel in [false, true] { + let mut panel = Panel::new(app(), draw); + let before = panel.app().session.tool_options_of(tool); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(typed); + panel.frame(); + let proposed = panel.app().session.tool_options_of(tool); + assert_ne!(proposed[key], before[key], "{label} changes while typing"); + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(tool), before, "{label} restores on Escape"); + } else { + panel.key(Key::Enter, Modifiers::NONE); + } + panel.frame(); + assert_eq!(panel.app().session.tool_options_of(tool), if cancel { before } else { proposed }); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "{label} only changes future tool options"); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/shared_edge.rs b/crates/ui-egui/src/addons/pathtools/shared_edge.rs index 0aeb9e17eb..a3d977cb94 100644 --- a/crates/ui-egui/src/addons/pathtools/shared_edge.rs +++ b/crates/ui-egui/src/addons/pathtools/shared_edge.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Shared Edges section: the Shared Edge Merge Tool's brush and -//! coincidence, and Keep Shared Points Together. +//! coincidence, and Keep Shared Points Together. Canceling a Diameter or Coincidence edit restores +//! its opening tool value; a retired edit supplies no replacement. use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _}; @@ -31,14 +32,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let diameter_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Diameter"), Bind::given(Some(diameter))).range(DIAMETER_RANGE.0..=DIAMETER_RANGE.1); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).events.landed()) }; if let Some(v) = row(ui, "Diameter", "shared-edge-diameter", diameter_field) { set = Some(json!({ "diameter": v })); } let coincidence_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Coincidence"), Bind::given(Some(tolerance))).range(0.0..=MAX_COINCIDENCE); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).events.landed()) }; if let Some(v) = row(ui, "Coincidence", "shared-edge-tolerance", coincidence_field) { set = Some(json!({ "tolerance": v })); diff --git a/crates/ui-egui/src/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.rs b/crates/ui-egui/src/dialogs.rs index 6fcff63221..4ee61440a0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -49,6 +49,7 @@ mod export_as; mod export_for_screens; pub(crate) mod export_host; pub mod eyedropper; +pub mod failed_plugins; pub mod file_info; pub mod find_links; pub mod find_replace; diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs index 58980c099c..dda71b4984 100644 --- a/crates/ui-egui/src/dialogs/action_new.rs +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -138,9 +138,7 @@ impl StackDialog for NewActionDialog { TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui); }); Field::new(label("Action Set:")).show(ui, |ui, _| { - if let Some(set) = Select::new(label("Action Set:"), Bind::given(fields.set), &sets).show(ui).value().copied() { - fields.set = set; - } + Select::new(label("Action Set:"), Bind::bound(&mut fields.set), &sets).show(ui); }); key_and_color(ui, &mut fields.options); automatic_align_options(ui, &mut fields.options); @@ -164,3 +162,110 @@ impl StackDialog for NewActionDialog { self.form.set_field(ctx, field, value) } } + +#[cfg(test)] +mod tests { + use craft::automation::actions::{ActionColor, ActionList}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use super::*; + use crate::dialogs::action_set_options::SetOptionsDialog; + use crate::panels::actions::{FUNCTION_KEYS, STOP_RECORDING, model}; + use crate::tests::panel_harness::Panel; + + fn panel() -> Panel { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.actions = ActionList::new(); + app.ui.actions.new_set("First").unwrap(); + app.ui.actions.new_set("Second").unwrap(); + app.ui.action_set = Some("First".into()); + Panel::new(app, crate::tests::picks::dialogs) + } + + fn fields(panel: &Panel) -> NewActionFields { + panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().form.values.clone()) + } + + fn popup(panel: &mut Panel, name: &str) { + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + } + + #[test] + fn cancelled_choices_keep_the_new_action_destination_key_and_color() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + let original = fields(&panel); + for name in ["Action Set", "Function Key", "Color"] { + popup(&mut panel, name); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + assert!(panel.enabled("Record")); + panel.click("Record"); + panel.frame(); + panel.frame(); + { + let app = panel.app(); + assert!(app.ui.recording.is_some()); + assert_eq!(model::members(&app.ui.actions, "First").len(), 1); + assert!(model::members(&app.ui.actions, "Second").is_empty()); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.name, original.name); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + panel.app().run(STOP_RECORDING, json!({})).unwrap(); + crate::dialogs::action_set_options::open_action(&mut panel.app(), 0, 0); + panel.frame(); + let options = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().json_fields().unwrap()); + let original = options(&panel); + for name in ["Function Key", "Color"] { + popup(&mut panel, name); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(options(&panel), original, "Action Options restores {name}"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + + #[test] + fn committed_choices_are_used_by_record() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + popup(&mut panel, "Action Set"); + panel.key(Key::Enter, Modifiers::NONE); + popup(&mut panel, "Color"); + panel.key(Key::Enter, Modifiers::NONE); + let key = (1..=FUNCTION_KEYS).find(|&key| key_reason(&ActionOptions { key, ..Default::default() }).is_none()).unwrap(); + panel.click_role("Function Key", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + for _ in 0..key { + panel.key(Key::ArrowDown, Modifiers::NONE); + } + panel.key(Key::Enter, Modifiers::NONE); + let chosen = fields(&panel); + assert_eq!((chosen.set, chosen.options.key, chosen.options.color), (1, key, ActionColor::ALL[1])); + panel.click("Record"); + panel.frame(); + panel.frame(); + let app = panel.app(); + assert!(model::members(&app.ui.actions, "First").is_empty()); + assert_eq!(model::members(&app.ui.actions, "Second").len(), 1); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, chosen.options.color); + assert_eq!(model::function_key(action).map(|key| key.key), Some(key)); + assert!(app.ui.recording.is_some()); + } +} diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 8a6de85fe4..10a0647fc9 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -243,9 +243,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let modifier = if crate::keymap::platform() == craft::keymap::Platform::Mac { "⌘" } else { "Ctrl" }; Field::new(label("Function Key:")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - if let Some(key) = Select::new(label("Function Key:"), Bind::given(options.key), &keys).show(ui).value().copied() { - options.key = key; - } + Select::new(label("Function Key:"), Bind::bound(&mut options.key), &keys).show(ui); Checkbox::new(Bind::bound(&mut options.cmd)).label(modifier).show(ui); Checkbox::new(Bind::bound(&mut options.shift)).label(label("Shift")).show(ui); }); @@ -255,9 +253,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let colors: Vec> = ActionColor::ALL.into_iter().map(|color| Entry::new(color, label_color_label(color.label_color(), &words))).collect(); Field::new(label("Color:")).show(ui, |ui, _| { - if let Some(color) = Select::new(label("Color:"), Bind::given(options.color), &colors).show(ui).value().copied() { - options.color = color; - } + Select::new(label("Color:"), Bind::bound(&mut options.color), &colors).show(ui); }); } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 1e3013b69a..4ca5f2fc23 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -23,10 +23,11 @@ use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; use craft::theme::Srgba; use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::Field; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::HostRequests; // PLAN: assumed re-export of the host requests the form output carries use craft::ui::patterns::form_dialogs::{FormCx, FormDialog, ResetFooter, ResetPick}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; @@ -351,7 +352,8 @@ fn length_row(ui: &mut Ui, label: impl Into