diff --git a/.github/workflows/cache-prune.yml b/.github/workflows/cache-prune.yml index a79f1ed907..c1b1e73ae3 100644 --- a/.github/workflows/cache-prune.yml +++ b/.github/workflows/cache-prune.yml @@ -1,11 +1,10 @@ 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). +# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache +# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg +# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once +# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions +# actions/cache-prune). on: workflow_run: workflows: [CI] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0954b5c35c..47f46692aa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: # Same craft-fonts commit as release.yml. - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c # 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. @@ -47,11 +47,14 @@ jobs: test-shards: 6 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # The warm build runs as one `cache warm /6` leg per shard, in parallel (each builds what + # its shard builds), and `cache warm` puts their files into the one entry it saves. + warm-split: true # 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-prune.yml deletes the one it replaced after each attempt. The nightly run restores + # nothing and builds everything from source. cache-workspace-crates: true cold-build: ${{ github.event_name == 'schedule' }} packages: >- @@ -59,46 +62,23 @@ jobs: 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 leg starts after `gate / select legs` and a - # free runner: the script fails when the leg has not started within 120 minutes, and then waits - # up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the - # script reports a leg that starts late with its own error before the job times out. + # free runner, and with `warm-split` after every `cache warm /6` leg. The script suspends its + # start deadline while any split leg is queued or running, then allows 180 minutes from the last + # split completion for the saving leg to start. Without split legs, it allows 180 minutes from + # the script's start. A failed split leg fails this job too. The script then waits up to 160 + # minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the + # script's deadlines expire when split builds or runner waits take too long. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 290 + timeout-minutes: 360 permissions: actions: write steps: diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index c74a3e83ab..4edc2fbfdc 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -29,7 +29,7 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: require-craft-fonts: true - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c run-package-check: true # The test builds of this workspace's largest crates (engine, ui-egui) need more than the # VM's 12 GB when two compile at once: the build was killed (exit 137) every night with diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 59536dcf36..2ae797d92d 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -47,7 +47,7 @@ jobs: - name: Check out craft-fonts uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main with: - ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c - id: rust uses: storytold/craft-common-actions/actions/rust-channel@main with: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index c2224a81ba..4d11ae3d96 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -28,7 +28,7 @@ jobs: tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c # One producer run builds every listed platform for one all-or-nothing release. The pin is the # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ea3bf92583..020f90e1ec 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,7 +44,7 @@ jobs: app-title: VectorCraft macos-runner: macos-15 macos-split-build: true - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c web-craft-fonts: true version: ${{ inputs.version }} contributors-artifact: ${{ needs.credits.outputs.artifact-name }} diff --git a/Cargo.lock b/Cargo.lock index 4c045af799..d0216e2962 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,9 +2165,10 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", + "craft-font-catalog", "craft-i18n", "craft-keymap", "craft-theme", @@ -2181,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "craft-behavior", @@ -2219,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2230,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2248,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2269,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2290,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "chrono", @@ -2341,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -2352,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2362,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "js-sys", "serde_json", @@ -2373,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "winsafe", ] @@ -2381,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2413,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2758,7 +2759,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "emath", @@ -2791,7 +2792,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2826,7 +2827,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit", "ahash", @@ -2845,7 +2846,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2864,7 +2865,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit_winit", "arboard", @@ -2889,7 +2890,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "egui", @@ -2903,7 +2904,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "egui", @@ -2916,7 +2917,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "dify", "eframe", @@ -2942,7 +2943,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", ] @@ -3023,7 +3024,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -3049,7 +3050,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -3772,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3781,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3799,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3817,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "hayro-ccitt", @@ -4805,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4962,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=30c3e72f47489d707c1c5657e16459dd362b5f2d#30c3e72f47489d707c1c5657e16459dd362b5f2d" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8573,7 +8574,6 @@ version = "0.25.1" dependencies = [ "craft-affinity", "craft-image-codecs", - "crc32fast", "proptest", "vectorcraft-affinity", ] @@ -9049,6 +9049,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/Cargo.toml b/Cargo.toml index f98e5919e2..843f9cbb53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # 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 = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # 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 = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # 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 = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,22 +194,22 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "30c3e72f47489d707c1c5657e16459dd362b5f2d" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/README.md b/README.md index 8e51d4930e..366b0711a8 100644 --- a/README.md +++ b/README.md @@ -233,8 +233,8 @@ VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the st and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the full parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked list of what's missing. -**Where we are (2026-10-10): alpha.** About 88% of core menu items, tools, effects and formats exist -(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday +**Where we are (2026-11-30): alpha.** About 96% of core menu items, tools, effects and formats exist +(99.9% of menu items do something), feature depth is ~79%, and we estimate ~65% ready for real work for a mainstream illustrator (~67% across all tracked features): everyday vector illustration is close to usable: drawing and path tools, Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package). diff --git a/ROADMAP.md b/ROADMAP.md index e317f148d8..84e40bc444 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -10,7 +10,7 @@ control channel. This page is the summary; the evidence is in [`docs/target-app- and the work list in [`docs/gaps.md`](docs/gaps.md). **Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance, -type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's +type, SVG/PDF/EPS, print, export) and feature depth is ~79%, but a professional can't yet switch: Illustrator's own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow @@ -24,8 +24,8 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | -| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~96%** | measured in part: menu items 815/816 wired (99.9%), tools 91/92, Illustrator effects 50/50, Photoshop effects 57/57, 3D 4/4 plus 3 Classic (initial types, graphics on the Materials page (#6960), no base materials) | +| **Feature depth** (weighted by use, scored by behaviour) | **~79%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -33,9 +33,9 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates | |---|---:|---:|---:|---| -| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem | +| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | +| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration). @@ -46,15 +46,15 @@ everything is measured from our code against Illustrator's public documentation. | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | 75% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) | -| UI/UX fidelity | 55% | 70–110 | [ui-parity.md](docs/ui-parity.md) | +| Features (depth) | 79% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) | +| UI/UX fidelity | 60% | 70–110 | [ui-parity.md](docs/ui-parity.md) | | File formats | 75% | 15–30 | [file-format-parity.md](docs/file-format-parity.md) | -| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) | -| Localization (12 key languages) | 74% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) | +| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) | +| Localization (12 key languages) | 87% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) | | Performance | ~60% | 15–25 | [gaps.md › G15](docs/gaps.md#g15-performance-budgets-and-a-gpu-renderer) | -| Stability | ~60% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) | -| Platforms | 80% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) | -| Ecosystem and plug-ins | 15% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) | +| Stability | ~55% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) | +| Platforms | 82% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) | +| Ecosystem and plug-ins | 30% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) | | AI features (generative) | 0% | 30–60 + owner decision | [gaps.md › G18](docs/gaps.md#g18-generative-ai-features) | | Agent automation | beyond Illustrator | — | [mcp.md](docs/mcp.md) | @@ -64,26 +64,26 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Area | % | One agent (h) | |---|---:|---:| -| Selection, transform & align | 85% | 4–6 | -| Drawing tools | 85% | 8–13 | -| Path operations, Pathfinder, Shape Builder, Live Paint | 80% | 4–8 | +| Selection, transform & align | 86% | 4–6 | +| Drawing tools | 88% | 8–13 | +| Path operations, Pathfinder, Shape Builder, Live Paint | 85% | 4–8 | | Colour, swatches, gradients, patterns, mesh, recolor | 92% | 4–7 | -| Strokes, brushes, width profiles | 88% | 8–15 | +| Strokes, brushes, width profiles | 90% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | -| Live vector effects | 85% | 4–8 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — | -| 3D and Materials | ~25% | 30–55 | -| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | -| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | -| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 | -| Image Trace, graphs, image tools | 75% | 5–8 | -| Layers, artboards, document setup | 78% | 5–8 | -| View & navigation | 70% | 9–14 | +| Live vector effects | 90% | 4–8 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 55% | — | +| 3D and Materials | ~35% | 30–55 | +| Type core — [type-parity.md](docs/type-parity.md) | 83% | 14–19 | +| Type advanced (CJK, spelling, Touch Type) | 60% | 20–28 | +| Symbols, blends, envelopes, Repeat, perspective | 90% | 4–7 | +| Image Trace, graphs, image tools | 78% | 5–8 | +| Layers, artboards, document setup | 82% | 5–8 | +| View & navigation | 80% | 9–14 | | Guides, grids, smart guides, snapping | 80% | 4–7 | | File formats — [file-format-parity.md](docs/file-format-parity.md) | 75% | 10–20 | -| Export for Screens, Asset Export, slices | 85% | 2–4 | +| Export for Screens, Asset Export, slices | 87% | 2–4 | | Print, colour management, separations | 80% | 2–4 | -| Automation (Actions, Variables, scripting) | 60% | 8–14 | +| Automation (Actions, Variables, scripting) | 80% | 8–14 | | UI chrome (panels, Properties, preferences) | 80% | 13–20 | | Libraries, Links, Package | 82% | 2–3 | | Generative AI | 0% | 30–60 | @@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Language | Code | Status | Translated | |---|---|---|---:| | English | `en` | full | 100% | -| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% | +| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% | | Spanish | `es` | full | 100% | | Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial | @@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h. 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. -4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h. +4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects (#5221, #885), Shape Builder regions and Asset Export borders are fixed): 6–13 h. 5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Progress log @@ -155,16 +155,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen arc size with Ctrl+wheel: over the canvas, a touchpad scroll or a mouse wheel turned with Ctrl makes the arc size 15° larger or smaller per step, as `]` and `[` do, and the view stays put (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`; part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). +- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected. - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged. - 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged. - 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. @@ -179,6 +183,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. +- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 376f431903..25cffe599e 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -48,3 +48,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "apps/vectorcraft/src/mac_fonts.rs", + "apps/vectorcraft/src/prefs_dir.rs", + "apps/vectorcraft/src/profile.rs", + "apps/vectorcraft/src/system_fonts.rs", + "apps/vectorcraft/src/windows_cores.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", +] diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..e4d26a0b6a 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -629,6 +629,7 @@ mod tests { /// On Windows `busy_cores` gives a number between 0 and the cores. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_how_many_cores_are_busy() { let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); @@ -639,6 +640,7 @@ mod tests { /// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than /// 10,000 MB. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_the_working_set() { let mb = rss_mb().map(|(mb, _)| mb); @@ -654,8 +656,7 @@ mod tests { let held = rss_mb(); drop(buffer); let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else { - eprintln!("no memory reading (Linux without `ps`): nothing to check"); - return; + panic!("rss_mb gave no memory reading"); }; assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}"); } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 54dfdebf82..70aae32f73 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { 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 = "30c3e72f47489d707c1c5657e16459dd362b5f2d", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index b91282e7da..2715e08125 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,4 +1,4 @@ -#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] +#[cfg(feature = "wgpu")] use super::gpu; use super::nightly_session; use super::prefs::{flush, save_tick}; @@ -44,7 +44,7 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - // The characters Alt + keypad codes typed (#5108). + // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). @@ -107,7 +107,7 @@ impl eframe::App for App { // Plug-ins still loading end before the launch marker does (the macOS exit below skips // dropping the app). self.app.session.cancel_plugin_loads(); - end_before_teardown(self.frames); + end_before_teardown(self.frames, self.graphics_loss.happened()); } } @@ -202,16 +202,58 @@ impl App { /// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the /// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed /// after the window, so it is ended here as `main` ends it after the window on other platforms. +/// On every platform, the process also ends here when the window's graphics device was lost +/// (`device_lost`, #6374). A frame the lost device could not present stays acquired, and releasing +/// the window's surface as eframe tears it down then panics in wgpu (gfx-rs/wgpu#9277). /// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics /// failure then starts the app again on another adapter (#651). -#[allow(unused_variables)] -fn end_before_teardown(frames: u64) { - #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] - if frames >= gpu::STARTUP_FRAMES { - safe_mode::end_launch(); - log::info!("quitting"); - log::logger().flush(); - std::process::exit(0); +fn end_before_teardown(frames: u64, device_lost: bool) { + if !ends_before_teardown(frames, device_lost) { + return; + } + if device_lost { + log::info!("the graphics device was lost: quitting before the window's graphics are torn down"); + } + // `main` does these after the window, which this exit skips. + #[cfg(not(target_os = "macos"))] + single_instance::resign(); + safe_mode::end_launch(); + log::info!("quitting"); + log::logger().flush(); + std::process::exit(0); +} + +/// Whether [`end_before_teardown`] ends the process: after the window's start-up, on macOS with +/// accessibility, or once the graphics device was lost. +#[cfg(feature = "wgpu")] +fn ends_before_teardown(frames: u64, device_lost: bool) -> bool { + frames >= gpu::STARTUP_FRAMES && (device_lost || cfg!(all(target_os = "macos", feature = "accessibility"))) +} + +/// Without wgpu there is no device-lost report, and the window is torn down as usual. +#[cfg(not(feature = "wgpu"))] +fn ends_before_teardown(_frames: u64, _device_lost: bool) -> bool { + false +} + +#[cfg(all(test, feature = "wgpu"))] +mod tests { + use vectorcraft_ui_egui::graphics::GraphicsLoss; + + use super::*; + + /// A device lost while the app runs ends the process before eframe releases the window's + /// surface, on every platform; before the window has started, the start-up restart takes over. + #[test] + fn a_lost_graphics_device_ends_the_process_before_teardown() { + let always = cfg!(all(target_os = "macos", feature = "accessibility")); + let (loss, ctx) = (GraphicsLoss::default(), egui::Context::default()); + assert_eq!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), always, "no loss: the usual teardown"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "a frame handles the report"); + assert!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), "after a loss the window is not torn down"); + assert!(!ends_before_teardown(gpu::STARTUP_FRAMES - 1, loss.happened()), "during start-up the adapter restart runs"); } } diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 198e7dcc85..f71cc434ba 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -32,6 +32,12 @@ //! that adapter, as the next one in the order would be tried. Each restart leaves out one more //! adapter, so it ends when none is left. //! +//! When no adapter is picked at all, because none is left or no graphics backend started (wgpu +//! needs Vulkan, OpenGL 3.3 or OpenGL ES 3.0, and the driver of Intel's Ironlake graphics offers +//! none of them, so the window's surface failed "for any enabled backend" with no backend listed, +//! #2654), Linux and the BSDs start once more on Mesa's software renderer ([`Software`]); after +//! that, the error that ends the app says what the graphics driver needs. +//! //! An adapter can also hang instead of failing: on a hybrid laptop with High Performance chosen, //! the discrete GPU never put the window's first frame on the screen, with no error and no panic, //! and the app stayed in the background without a window (#964). [`watch_first_frame`] gives the @@ -853,7 +859,7 @@ pub fn watch_first_frame(startup: Arc) { // The new app records its own start. startup.ended(); skip.push(failed.to_string()); - match restart(&skip.join(",")) { + match restart(&skip.join(","), false) { Ok(()) => std::process::exit(0), Err(e) => { log::error!("starting again failed: {e}"); @@ -950,6 +956,94 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p)) } +/// Whether a start whose window no graphics adapter could show may start again on Mesa's software +/// renderer, which draws OpenGL on the CPU (llvmpipe). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Software { + /// Linux and the BSDs, where Mesa provides OpenGL, and this start isn't on it yet. + Possible, + /// This start already draws on it: the app started again with [`SOFTWARE_ENV`], or the user + /// set `LIBGL_ALWAYS_SOFTWARE`. + Tried, + /// Windows and macOS, or a start that `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` chooses. + Unavailable, +} + +impl Software { + /// This start's [`Software`], from the platform and the environment. + pub fn from_env() -> Self { + if cfg!(any(windows, target_os = "macos")) || explicit_choice() { + Software::Unavailable + } else if software_start() || std::env::var_os("LIBGL_ALWAYS_SOFTWARE").is_some() { + Software::Tried + } else { + Software::Possible + } + } +} + +/// Set by the app when it starts again on Mesa's software renderer because no graphics adapter +/// could show the window (#2654). +pub const SOFTWARE_ENV: &str = "VECTORCRAFT_GPU_SOFTWARE"; + +/// Whether this start is the one the app made on Mesa's software renderer ([`SOFTWARE_ENV`]). +pub fn software_start() -> bool { + std::env::var_os(SOFTWARE_ENV).is_some() +} + +/// The graphics APIs the window can draw with on this platform, for the error that ends the app +/// when no adapter can show it and for the note of a start on Mesa's software renderer. +pub const NEEDS: &str = if cfg!(windows) { + "Direct3D 12, OpenGL 3.3 or OpenGL ES 3.0" +} else if cfg!(target_os = "macos") { + "Metal" +} else { + "Vulkan, OpenGL 3.3 or OpenGL ES 3.0" +}; + +/// What follows the window's run ([`next`]). +#[derive(Debug, PartialEq, Eq)] +enum Next { + /// The window closed normally. + Done, + /// Start again without the adapters in `skip`, on Mesa's software renderer when `software`. + Restart { skip: Vec, software: bool }, + /// End the app with this error. + Stop(String), +} + +/// What follows the window's run: `why` it failed (`None` when it closed normally), whether the +/// graphics failed, the `frames` the UI ran, the adapter `picked`, those left out (`skip`) and +/// whether the software renderer is still to try. A failure on an adapter while starting up starts +/// again without it. When no adapter was picked, because none can show the window or no graphics +/// backend started at all (an old GPU whose driver offers neither Vulkan nor OpenGL 3.3 or OpenGL +/// ES 3.0, such as Intel's Ironlake graphics, #2654), Linux and the BSDs start once more on Mesa's +/// software renderer, and after that the error says what the window needs. +fn next(why: Option, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec, software: Software) -> Next { + let Some(why) = why else { return Next::Done }; + if let Some(failed) = restart_without(graphics_failed, frames, picked, &skip) { + log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); + skip.push(failed.to_string()); + return Next::Restart { skip, software: false }; + } + if !graphics_failed { + return Next::Stop(why); + } + if picked.is_some() || frames >= STARTUP_FRAMES { + return Next::Stop(format!("{why} ({HELP})")); + } + match software { + Software::Possible => { + log::error!("no graphics adapter could show the window ({why}): starting again on Mesa's software renderer, which draws on the CPU"); + Next::Restart { skip, software: true } + } + Software::Tried => Next::Stop(format!( + "{why}: no graphics adapter could show the window, not even Mesa's software renderer (the graphics driver needs {NEEDS}; {HELP})" + )), + Software::Unavailable => Next::Stop(format!("{why}: no graphics adapter could show the window (the graphics driver needs {NEEDS}; {HELP})")), + } +} + /// After the window's run: `Ok` when it closed normally or the app started again (see the module /// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that /// ended it. @@ -957,28 +1051,35 @@ pub fn finish(outcome: Result, startup: &Startup) -> Res // Whatever follows, this start didn't crash; a new app records its own start. startup.ended(); let (why, graphics_failed) = match outcome { - Ok(Ok(())) => return Ok(()), - Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true), - Ok(Err(e)) => (e.to_string(), false), - Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)), + Ok(Ok(())) => (None, false), + Ok(Err(e @ eframe::Error::Wgpu(_))) => (Some(e.to_string()), true), + Ok(Err(e)) => (Some(e.to_string()), false), + Err(panic) => (Some(panic), GRAPHICS_PANIC.load(Ordering::Relaxed)), }; let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr); - let mut skip = skipped(); - let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else { - return Err(if graphics_failed { format!("{why} ({HELP})") } else { why }); - }; - log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); - skip.push(failed.to_string()); - restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}")) + let picked = startup.adapter.get().map(String::as_str); + match next(why.clone(), graphics_failed, frames, picked, skipped(), Software::from_env()) { + Next::Done => Ok(()), + Next::Stop(e) => Err(e), + Next::Restart { skip, software } => { + let why = why.unwrap_or_default(); + restart(&skip.join(","), software).map_err(|e| format!("{why}; starting again failed: {e}")) + } + } } -/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the -/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and -/// this returns only on failure; on Windows it starts beside this one, which then exits. -fn restart(skip: &str) -> std::io::Result<()> { +/// Start the app again with the same arguments, leaving out the adapters in `skip`, and on Mesa's +/// software renderer when `software` (`LIBGL_ALWAYS_SOFTWARE`, with [`SOFTWARE_ENV`] so it is +/// tried once). On Unix the new app replaces this process (same process id, so an AppImage keeps +/// its files mounted), and this returns only on failure; on Windows it starts beside this one, +/// which then exits. +fn restart(skip: &str, software: bool) -> std::io::Result<()> { log::logger().flush(); let mut c = std::process::Command::new(std::env::current_exe()?); c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip); + if software { + c.env("LIBGL_ALWAYS_SOFTWARE", "1").env(SOFTWARE_ENV, "1"); + } #[cfg(unix)] { use std::os::unix::process::CommandExt as _; diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 792518993d..118a78006c 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() { let saved = prefs.to_json(); assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); } - // Every choice Preferences offer means something here. - for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { - assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); - } + // Preferences offer the three choices read above, and no other. + let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect(); + assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]); } #[test] @@ -602,15 +601,52 @@ fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() { fn a_normal_exit_or_another_failure_does_not_restart() { let startup = Startup::default(); assert_eq!(finish(Ok(Ok(())), &startup), Ok(())); - // No adapter was picked (none can show the window): the error is returned, nothing restarts. - let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into())); - assert_eq!( - finish(Ok(Err(none)), &startup), - Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})")) - ); let _ = startup.adapter.set("Vulkan:1002:164e".into()); GRAPHICS_PANIC.store(false, Ordering::Relaxed); assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); + // The same, decided without starting anything. + let amd = Some("Vulkan:1002:164e"); + for software in [Software::Possible, Software::Tried, Software::Unavailable] { + assert_eq!(next(None, false, 0, amd, vec![], software), Next::Done); + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], software), Next::Stop("a bug".into())); + // A failure after start-up, or on an adapter already left out, is not the start's. + assert_eq!(next(Some("lost".into()), true, STARTUP_FRAMES, amd, vec![], software), Next::Stop(format!("lost ({HELP})"))); + let skip = vec!["Vulkan:1002:164e".to_string()]; + assert_eq!(next(Some("lost".into()), true, 0, amd, skip, software), Next::Stop(format!("lost ({HELP})"))); + } + // An adapter that failed while starting up is left out, never with the software renderer. + assert_eq!( + next(Some("lost".into()), true, 0, amd, vec!["Gl:8086:0046".into()], Software::Possible), + Next::Restart { skip: vec!["Gl:8086:0046".into(), "Vulkan:1002:164e".into()], software: false } + ); +} + +/// #2654: on a ThinkPad T510 with Intel's Ironlake graphics, whose driver offers neither Vulkan +/// nor OpenGL 3.3 or OpenGL ES 3.0, wgpu started no backend, so the window's surface failed before +/// any adapter was listed and the app ended; started with `LIBGL_ALWAYS_SOFTWARE=1`, it ran on +/// llvmpipe. With no adapter picked, Linux starts once more on Mesa's software renderer, keeping +/// the adapters already left out, and the error after that says what the driver needs. +#[test] +fn a_start_no_adapter_can_show_tries_the_software_renderer_once() { + let surface = "WGPU error: Failed to create surface for any enabled backend: {}"; + let skip = vec!["Vulkan:8086:0046".to_string()]; + assert_eq!(next(Some(surface.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // No adapter left that can show the window, after restarts without each. + let none = "WGPU error: Adapter selection failed: no graphics adapter can show the window"; + assert_eq!(next(Some(none.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // Already on the software renderer: the app ends, saying what the window needs. + let Next::Stop(tried) = next(Some(surface.into()), true, 0, None, skip.clone(), Software::Tried) else { + panic!("a start already on the software renderer starts again") + }; + assert!(tried.starts_with(surface), "{tried}"); + assert!(tried.contains("not even Mesa's software renderer") && tried.contains(NEEDS) && tried.contains(HELP), "{tried}"); + // Windows, macOS or a backend the user chose: no software renderer to start on. + let Next::Stop(unavailable) = next(Some(surface.into()), true, 0, None, skip, Software::Unavailable) else { + panic!("a start without the software renderer starts again") + }; + assert!(unavailable.contains(NEEDS) && unavailable.contains(HELP) && !unavailable.contains("Mesa"), "{unavailable}"); + // A failure outside the graphics never starts again. + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], Software::Possible), Next::Stop("a bug".into())); } /// A log folder of its own for each test. diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs index 5714b8c548..5039c89bd1 100644 --- a/apps/vectorcraft/src/hang_watch.rs +++ b/apps/vectorcraft/src/hang_watch.rs @@ -3,8 +3,8 @@ //! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the //! log (`logs/vectorcraft.log`) and to `logs/hang-report-.txt`: the stage, a clipboard //! call in progress, the last commands, the last frames' times, the platform, the window system, the -//! graphics processor and the present mode the app asked for, and how long the session has run with -//! how many documents open. The process holds a lock on the file until the interface thread answers +//! graphics processor, its driver when known, and the present mode the app asked for, and how long +//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers //! again; then the log says after how long and the file is removed. A file nobody holds at a later //! launch was left by a session that was closed while it did not answer, and a locked one belongs to //! another instance that is stalled now and is left alone. That launch writes the report to the log, @@ -113,6 +113,8 @@ pub struct Facts { pub flatpak: bool, /// The graphics processor the window draws with. pub graphics: Option, + /// The active graphics driver's identity, when the backend reports it. + graphics_driver: Option, /// The present mode and frame queue the app asked the window surface for. pub surface: String, } @@ -128,14 +130,29 @@ impl Facts { session_type: value("XDG_SESSION_TYPE"), flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()), graphics, + graphics_driver: None, surface, } } + #[cfg(any(feature = "wgpu", test))] + pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts { + // D3D12 reports 0.0.0.0 when the driver version could not be read. + let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0"); + self.graphics_driver = fields.next().map(|mut detail| { + if let Some(info) = fields.next().filter(|info| info != &detail) { + detail.push_str(" / "); + detail.push_str(&info); + } + detail + }); + self + } + /// The facts as report lines. pub fn lines(&self) -> String { let or_unknown = |v: &Option| v.clone().unwrap_or_else(|| "unknown".to_string()); - format!( + let mut lines = format!( "VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n", vectorcraft_ui_egui::os_window::version(), std::env::consts::OS, @@ -146,7 +163,13 @@ impl Facts { if self.flatpak { "yes" } else { "no" }, or_unknown(&self.graphics), self.surface, - ) + ); + if let Some(driver) = &self.graphics_driver { + lines.push_str("Graphics driver: "); + lines.push_str(driver); + lines.push('\n'); + } + lines } } diff --git a/apps/vectorcraft/src/hang_watch/tests.rs b/apps/vectorcraft/src/hang_watch/tests.rs index 7452d41502..608d6e9b78 100644 --- a/apps/vectorcraft/src/hang_watch/tests.rs +++ b/apps/vectorcraft/src/hang_watch/tests.rs @@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() { assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n")); assert!(text.contains("Recent commands, oldest first: none")); } + +#[test] +fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() { + let mut shared = shared(None); + let beacon = Beacon::new(); + for (driver, info, expected) in [ + (" 32.0.16.1088 ", "", Some("32.0.16.1088")), + ("32.0.16.2124", "", Some("32.0.16.2124")), + ("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")), + ("Mesa", "Mesa", Some("Mesa")), + ("0.0.0.0", "", None), + ("", "", None), + ] { + shared.facts = facts().with_graphics_driver(driver, info); + let text = troubleshooting(&shared, &beacon, UNIX_EPOCH); + assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report"); + assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected); + } +} diff --git a/apps/vectorcraft/src/mac_color_space.rs b/apps/vectorcraft/src/mac_color_space.rs index 3fa1394804..ccdb340ec2 100644 --- a/apps/vectorcraft/src/mac_color_space.rs +++ b/apps/vectorcraft/src/mac_color_space.rs @@ -99,6 +99,7 @@ mod tests { } /// A layer without a color space is tagged sRGB once; the second call leaves it as it is. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn an_untagged_layer_becomes_srgb() { let layer = CAMetalLayer::new(); @@ -110,6 +111,7 @@ mod tests { } /// A layer with a color space of its own keeps it. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_layer_with_a_color_space_keeps_it() { let layer = CAMetalLayer::new(); @@ -121,6 +123,7 @@ mod tests { /// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal /// layers are returned. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn metal_layers_are_found_under_the_view_layer() { let metal = CAMetalLayer::new(); diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index 36223c559f..4e9f996d62 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -52,6 +52,7 @@ mod tests { use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL}; /// CoreText lists the installed fonts, by their files' full paths. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn coretext_lists_the_installed_font_files() { let files = super::font_files(); @@ -61,6 +62,7 @@ mod tests { /// A font registered with CoreText from another folder, as apps and font managers register /// fonts, is listed while it is registered. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn fonts_registered_from_other_folders_are_listed() { let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c3c20a583d..2304d232b7 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -385,21 +385,48 @@ fn read_command_line( /// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`). #[cfg(target_os = "linux")] fn opens_through_xwayland(pref: Option<&str>) -> bool { - if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { + use xwayland::Choice; + let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached); + // On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there. + match &choice { + Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {} + Choice::NoXDisplay { x11: true } => { + log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland") + } + Choice::NoXDisplay { x11: false } => log::info!( + "opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland" + ), + Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"), + Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"), + Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"), + } + if !choice.xwayland() { return false; } if !xwayland::x11_libraries_found() { - log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + if let Choice::Pen(name) = &choice { + log::warn!( + "pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it" + ); + } else { + log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + } return false; } - if pref != Some("x11") { - log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); + if let Choice::Pen(name) = &choice { + log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } true } +/// The docking runtime needs the backend the desktop window is opened on. +fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo { + let backend = if forced_to_x11 { Backend::X11 } else { detected }; + ShellInfo::current().backend(backend) +} + /// The nightly channel this build is, as a string for the log. fn channel_name() -> &'static str { match build_flavor::COMPILED { @@ -686,10 +713,10 @@ fn main() -> std::process::ExitCode { // A window forced onto XWayland runs on X11, whose window manager draws the frame: the // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and // Preferences › User Interface › System Title Bar. - let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11); // On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted // beside it (#2450, #5311). - let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland; + let wayland = shell_info.backend == Backend::Wayland; let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing); let shell_info = shell_info.caps(caps); let titlebar_pref = @@ -711,14 +738,14 @@ fn main() -> std::process::ExitCode { // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the - // characters Alt + keypad codes type (`windows_alt_codes`). + // keypad digits of Alt + keypad codes (`windows_alt_codes`). #[cfg(windows)] let options = { use winit::platform::windows::EventLoopBuilderExtWindows as _; let mut options = options; options.event_loop_builder = Some(Box::new(|builder| { builder.with_msg_hook(|msg| { - // Alt + keypad codes (#5108), which winit drops; neither hook consumes a message. + // Alt + keypad codes (#5108); neither hook consumes a message. windows_alt_codes::msg_hook(msg); windows_stylus::msg_hook(msg) }); @@ -909,7 +936,13 @@ fn main() -> std::process::ExitCode { let summary = adapter_summary(&rs.adapter.get_info()); log::info!("rendering with {summary} (power preference {power:?})"); created.created(&cc.egui_ctx); - if !gpu::skipped().is_empty() { + if gpu::software_start() { + // No graphics processor could show the window, so Mesa draws it on the CPU (#2654). + app.status(format!( + "No graphics processor could show the window, so VectorCraft started again on {summary}, which draws on the CPU and is slower. Showing it on the graphics processor needs a driver with {}", + gpu::NEEDS + )); + } else if !gpu::skipped().is_empty() { // A processor chosen in Settings can be the one that can't show the window. if chosen_gpu { app.status(format!( @@ -943,14 +976,22 @@ fn main() -> std::process::ExitCode { .map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency)); #[cfg(not(feature = "wgpu"))] let surface = None; + let facts = hang_watch::Facts::new( + |name| std::env::var(name).ok(), + std::path::Path::new("/.flatpak-info").exists(), + hang_watch::window_system(winit_window.as_deref()), + app.graphics_adapter.clone(), + hang_watch::surface(surface), + ); + #[cfg(feature = "wgpu")] + let facts = if let Some(rs) = &cc.wgpu_render_state { + let info = rs.adapter.get_info(); + facts.with_graphics_driver(&info.driver, &info.driver_info) + } else { + facts + }; let hang = std::sync::Arc::new(hang_watch::Shared { - facts: hang_watch::Facts::new( - |name| std::env::var(name).ok(), - std::path::Path::new("/.flatpak-info").exists(), - hang_watch::window_system(winit_window.as_deref()), - app.graphics_adapter.clone(), - hang_watch::surface(surface), - ), + facts, started: std::time::Instant::now(), last: std::sync::Mutex::new(None), previous: previous_hang.clone(), diff --git a/apps/vectorcraft/src/open_documents.rs b/apps/vectorcraft/src/open_documents.rs index 67f409b0e8..a126618ee0 100644 --- a/apps/vectorcraft/src/open_documents.rs +++ b/apps/vectorcraft/src/open_documents.rs @@ -94,6 +94,7 @@ mod tests { use super::*; /// Files queue until the UI takes them; URLs that aren't files are left out. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn opened_files_wait_for_the_ui() { let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap(); diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index 09c57f22e4..636b8c81ef 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; use std::time::{Duration, Instant}; -use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings}; +use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SectionError, SettingsStore, SharedSettings}; use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy}; use super::{VectorcraftApp, prefs_dir}; @@ -18,6 +18,15 @@ fn legacy_dir() -> Option { prefs_dir::profile::prefs_dir(true) } +/// Parses the one `ui.json` slot of a legacy import: its bytes, or why it could not be read. +fn parse_legacy_slot(slots: &[Result, &std::io::Error>]) -> Result<(AppSettings, Vec), String> { + match slots.first() { + Some(Ok(Some(bytes))) => parse_legacy(bytes), + Some(Err(e)) => Err(e.to_string()), + _ => Err("the preferences file is missing".to_string()), + } +} + /// Where the log files live: `logs` in the preferences folder (see `logging`). pub(crate) fn log_dir() -> Option { Some(prefs_dir::prefs_dir()?.join("logs")) @@ -34,7 +43,7 @@ pub(crate) fn prefs_enabled() -> bool { pub(crate) fn open_store() -> (SharedSettings, LoadReport) { let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) { Some(dir) => { - let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy }; + let file = |dir: PathBuf| LegacyFile { paths: vec![dir.join(LEGACY_FILE)], parse: parse_legacy_slot }; let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect(); (Location::Dir(dir), legacy) } diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index fb28192f05..21744a7ada 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -28,6 +28,9 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn scripts_may_print(&self) -> bool { + true + } } /// The status after the job `title` went to `printer` (the default one without a name), with the diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index 4dd8f7d9ec..2c6a8b68c1 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -41,7 +41,7 @@ //! the rotation's range is 0°, and an axis a pen lacks reads nothing. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft::behavior::PointerSample; use craft::ui::runtime::pen::PenSource; @@ -189,6 +189,8 @@ enum Update { struct Pens { devices: HashMap, last: HashMap; 5]>, + /// The pens an event has come from, for the log. + heard: HashSet, } impl Pens { @@ -197,10 +199,37 @@ impl Pens { /// same id starts without them. fn set_devices(&mut self, devices: impl IntoIterator) { let devices: HashMap = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d))); + let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)); + self.last.retain(|id, _| unchanged(id)); + self.heard.retain(|id| unchanged(id)); self.devices = devices; } + /// The names of the pens listed, by device id, for the log. + fn pen_names(&self) -> Vec<&str> { + let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect(); + pens.sort_by_key(|d| d.id); + pens.into_iter().map(|d| d.name.as_str()).collect() + } + + /// The pens listed, as the log line says it: under XWayland on a Wayland session this tells + /// whether XWayland lists the pen at all (#5622). + fn summary(&self) -> String { + let names = self.pen_names(); + if names.is_empty() { + "the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string() + } else { + format!("pens listed: {}", names.join(", ")) + } + } + + /// The name of pen `id` when this is the first event from it since it was listed, for the log: + /// it tells whether the pen's events reach the app at all. + fn first_event(&mut self, id: u16) -> Option<&str> { + let device = self.devices.get(&id).filter(|d| d.is_pen())?; + self.heard.insert(id).then_some(device.name.as_str()) + } + /// A raw motion or button event of device `id`, with the valuators that changed. fn handle(&mut self, id: u16, valuators: impl IntoIterator) -> Update { let Some(device) = self.devices.get(&id) else { return Update::Keep }; @@ -231,6 +260,9 @@ impl Pens { /// A raw event as the X server sends it: its valuator mask and the values of the valuators /// set in it. A pen's sample or another pointer's `None` goes into `pen`. fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) { + if let Some(name) = self.first_event(id) { + log::info!("tablet: events arrive from the pen {name:?}"); + } if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { pen.set(sample); } @@ -304,6 +336,7 @@ mod x11 { .map_err(|e| format!("XISelectEvents failed: {e}"))?; let mut pens = Pens::default(); pens.set_devices(query_devices(&conn)); + log::info!("tablet: {}", pens.summary()); std::thread::Builder::new() .name("vectorcraft-tablet-x11".into()) .spawn(move || run(&conn, &mut pens, &pen)) @@ -321,7 +354,14 @@ mod x11 { let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values); } - Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), + Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => { + let before = pens.summary(); + pens.set_devices(query_devices(conn)); + let after = pens.summary(); + if after != before { + log::info!("tablet: {after}"); + } + } _ => {} } } @@ -623,6 +663,31 @@ mod tests { assert!(s.pressure < 0.001, "{}", s.pressure); } + /// #5622: the log names the pens the X server lists (XWayland's included) and the first event + /// from each, once, again after the pen is listed anew, and never for a mouse. + #[test] + fn the_log_names_the_pens_listed_and_the_first_event_from_each() { + let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators()); + let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators()); + let mut pens = Pens::default(); + assert!(pens.summary().contains("lists no pen"), "{}", pens.summary()); + pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]); + assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16"); + assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16")); + assert_eq!(pens.first_event(11), None, "once"); + assert_eq!(pens.first_event(4), None, "a mouse"); + assert_eq!(pens.first_event(99), None, "a device not listed"); + // Listed again unchanged: still heard. Another device under the same id: heard anew. + pens.set_devices([eraser.clone(), mouse(4), stylus]); + assert_eq!(pens.first_event(11), None); + pens.set_devices([eraser, mouse(4), pen(11)]); + assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus")); + // The events go into the feed as before. + let source = PenSource::default(); + pens.raw_event(&source, 12, &[0b100], &[65535.0]); + assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0))); + } + #[test] fn fixed_point_values() { assert_eq!(fp3232(3, 1 << 31), 3.5); diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 838d96845a..c28fb19c13 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -1,5 +1,18 @@ use super::*; +#[test] +fn desktop_shell_reports_the_backend_selected_for_docking() { + let wayland = desktop_shell_info(Backend::Wayland, false); + assert_eq!(wayland.backend, Backend::Wayland); + assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window"); + + for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] { + let x11 = desktop_shell_info(detected, force_x11); + assert_eq!(x11.backend, Backend::X11); + assert!(x11.window_positions(), "X11 and XWayland can place native palettes"); + } +} + /// The saved UI state of an old `ui.json`, as the legacy import reads it. fn legacy_ui(bytes: &[u8]) -> Option { vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui) diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index 0abf65ddc9..c358a65653 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -4,14 +4,12 @@ //! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows -//! (). winit -//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which -//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees -//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes -//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed -//! text, so the Type tool (or a panel's text field) types it like any other character, in the -//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame, -//! so they don't run a shortcut bound to Alt and a digit. +//! (). winit reports +//! that character as a key press of its own with the character as its text (storytold/winit W36), +//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives +//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message +//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad +//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -29,11 +27,11 @@ use std::cell::RefCell; use egui::{Event, Key}; +#[cfg(windows)] const WM_KEYDOWN: u32 = 0x0100; -const WM_KEYUP: u32 = 0x0101; -const WM_CHAR: u32 = 0x0102; const WM_SYSKEYDOWN: u32 = 0x0104; const WM_SYSKEYUP: u32 = 0x0105; +#[cfg(windows)] const WM_SYSCHAR: u32 = 0x0106; /// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. const VK_NUMPAD0: usize = 0x60; @@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key:: /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; -/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt. -const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5]; thread_local! { /// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it. static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue. +/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { - /// Keypad digits typed while Alt has been held. - digits: usize, - /// Alt came up after keypad digits: the next character message is the code's character. - armed: bool, - /// A high surrogate waiting for its low half. - high: Option, - /// Characters the codes typed, for the next frame. - typed: String, /// The digits of the keypad presses and releases with Alt held since the last frame, which /// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken /// out of the frame. @@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option { impl AltCodes { /// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit) - /// and `lparam` (its flags). + /// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system + /// key. fn message(&mut self, message: u32, wparam: usize, lparam: isize) { - let keypad = match message { - WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam), - _ => None, - }; - if let Some(d) = keypad { - // Windows sends a key pressed with Alt held as a system key. - if message == WM_SYSKEYDOWN { - self.digits += 1; - self.armed = false; - } + if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP) + && let Some(d) = keypad_digit(wparam, lparam) + { self.keypad_events.push(d); - return; - } - match message { - WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {} - // Any other key ends the sequence and keeps its own meaning. - WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(), - WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => { - self.armed = self.digits > 0; - self.digits = 0; - } - WM_CHAR | WM_SYSCHAR if self.armed => { - let unit = (wparam & 0xffff) as u16; - if (0xd800..0xdc00).contains(&unit) { - self.high = Some(unit); - return; - } - let units: Vec = self.high.take().into_iter().chain([unit]).collect(); - self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control())); - self.armed = false; - } - _ => {} } } - fn reset(&mut self) { - self.digits = 0; - self.armed = false; - self.high = None; - } - - /// Hand the frame `events` the characters typed since the last frame, as typed text, and take - /// out the keypad digits typed with Alt held. + /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. + /// The character a code types comes from winit, as typed text. fn drain(&mut self, events: &mut Vec) { let mut keypad = std::mem::take(&mut self.keypad_events); - if !keypad.is_empty() { - events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { - return true; - }; - if !modifiers.alt { - return true; - } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { - Some(i) => { - keypad.remove(i); - false - } - None => true, - } - }); - } - if !self.typed.is_empty() { - events.push(Event::Text(std::mem::take(&mut self.typed))); + if keypad.is_empty() { + return; } + events.retain(|e| { + let Event::Key { key, modifiers, .. } = e else { + return true; + }; + if !modifiers.alt { + return true; + } + // The first keypad key still to take out that egui reports as `key`. + let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); + match keypad.iter().position(stands_for) { + Some(i) => { + keypad.remove(i); + false + } + None => true, + } + }); } } -/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type, -/// and hands each message to `windows_symbol_chars`. It never consumes the message. +/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands +/// each message to `windows_symbol_chars`. It never consumes the message. #[cfg(windows)] #[allow(unsafe_code)] pub fn msg_hook(msg: *const std::ffi::c_void) { @@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text. +/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. pub fn raw_input_hook(raw: &mut egui::RawInput) { CODES.with(|c| { if let Ok(mut c) = c.try_borrow_mut() { @@ -196,6 +149,9 @@ mod tests { use super::*; const ALT: usize = 0x12; + const WM_KEYDOWN: u32 = 0x0100; + const WM_KEYUP: u32 = 0x0101; + const WM_CHAR: u32 = 0x0102; /// Alt held, keypad digits `code`, Alt released, and the character Windows then posts. fn alt_code(c: &mut AltCodes, code: &str, posted: u16) { @@ -215,59 +171,53 @@ mod tests { } #[test] - fn an_alt_code_types_its_character_when_alt_comes_up() { + fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { let mut c = AltCodes::default(); alt_code(&mut c, "0176", 0xB0); alt_code(&mut c, "0151", 0x2014); - let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)]; + // winit reports each code's character as typed text. + let mut events = vec![ + key(Key::Num0, true, true), + key(Key::Num0, true, false), + key(Key::Num1, false, true), + Event::Text("°".into()), + Event::Text("—".into()), + ]; c.drain(&mut events); // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and the characters follow. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]); + // the digit typed without Alt stays, and each character stays once. + assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); let mut events = vec![key(Key::Num0, true, true)]; c.drain(&mut events); assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); } #[test] - fn a_character_without_a_code_before_it_is_left_to_winit() { + fn characters_are_left_to_winit() { let mut c = AltCodes::default(); - // A plain key press's character (winit types it), and Alt pressed and released alone. + // A plain key press's character, Alt pressed and released alone, and a code's character. c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_KEYUP, ALT, 0); c.message(WM_CHAR, usize::from(b'b'), 0); + alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); } #[test] - fn another_key_while_alt_is_held_cancels_the_code() { + fn alt_with_another_key_keeps_its_shortcut() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); - let mut events = vec![]; + let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; c.drain(&mut events); - assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}"); - } - - #[test] - fn a_code_above_the_basic_plane_arrives_as_two_halves() { - let mut c = AltCodes::default(); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0xD83D, 0); - c.message(WM_CHAR, 0xDE00, 0); - let mut events = vec![]; - c.drain(&mut events); - assert_eq!(events, vec![Event::Text("😀".into())]); + assert_eq!(events, vec![key(Key::F, true, true)]); } /// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the @@ -284,7 +234,7 @@ mod tests { } #[test] - fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() { + fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a @@ -296,7 +246,7 @@ mod tests { } events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]); + assert_eq!(events, vec![key(Key::Home, false, true)]); } #[test] @@ -309,11 +259,11 @@ mod tests { let mut events = vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; c.drain(&mut events); - assert_eq!(events, vec![Event::Text("—ê".into())]); + assert!(events.is_empty(), "{events:?}"); } #[test] - fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() { + fn the_separate_navigation_keys_still_move_the_caret() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0); @@ -322,7 +272,6 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 38b210c05e..1471f44199 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -22,18 +22,61 @@ use std::path::{Path, PathBuf}; const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; -/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and -/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after -/// the other checks. -pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { +/// What the pen check found: the name of the first pen, `None` when there is none, or why the +/// device list could not be read. +pub type PenProbe = Result, String>; + +/// Where the window opens, and why, as [`choose`] decides it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Choice { + /// Not a Wayland session: the window opens where winit opens it. + NotWayland, + /// XWayland, because Linux Display Server is X11 (XWayland). + Chosen, + /// XWayland, because the pen of this name is attached. + Pen(String), + /// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland + /// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen. + NoXDisplay { x11: bool }, + /// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there. + NativeWayland, + /// Wayland: no pen is attached. + NoPen, + /// Wayland: the input devices could not be listed, for this reason. + NoDeviceList(String), +} + +impl Choice { + /// Whether the window opens through XWayland. + pub fn xwayland(&self) -> bool { + matches!(self, Self::Chosen | Self::Pen(_)) + } +} + +/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11` +/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen +/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland +/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs +/// only after the other checks. +pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> PenProbe) -> Choice { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); - let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); - let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); - match pref { - Some("x11") => session, - _ => session && !native_wayland && pen(), + if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") { + return Choice::NotWayland; + } + let x11 = pref == Some("x11"); + if !set("DISPLAY") { + return Choice::NoXDisplay { x11 }; + } + if x11 { + return Choice::Chosen; + } + if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") { + return Choice::NativeWayland; + } + match pen() { + Ok(Some(name)) => Choice::Pen(name), + Ok(None) => Choice::NoPen, + Err(e) => Choice::NoDeviceList(e), } } @@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140; const ABS_X: u32 = 0x00; const ABS_Y: u32 = 0x01; -/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen. -pub fn pen_attached() -> bool { - std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)) +/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read. +pub fn pen_attached() -> PenProbe { + std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}")) } -/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose +/// Is a pen among the input devices `/proc/bus/input/devices` lists? +#[cfg(test)] +fn has_pen(devices: &str) -> bool { + find_pen(devices).is_some() +} + +/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its +/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose /// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as /// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code, /// `BTN_TOOL_PEN` included, but has no absolute axes. -fn has_pen(devices: &str) -> bool { - devices.split("\n\n").any(|device| { - let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); - bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) - && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) +fn find_pen(devices: &str) -> Option { + devices.split("\n\n").find_map(|device| { + let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); + let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) + && field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)); + pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string())) }) } @@ -147,6 +198,11 @@ mod tests { panic!("the pen check ran") } + /// [`choose`] as a yes or no, with a pen check that finds a pen or none. + fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { + choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland() + } + #[test] fn xwayland_only_when_chosen_on_wayland_with_an_x_display() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); @@ -183,6 +239,40 @@ mod tests { assert!(wanted(Some("x11"), &native, no_probe)); } + /// #5622: the choice names why the window stays on Wayland, where the pen does not reach it, + /// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen + /// that is not listed or a device list that can't be read. + #[test] + fn the_choice_says_why_the_window_stays_on_wayland() { + let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); + let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string())); + let never = || -> PenProbe { panic!("the pen check ran") }; + assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland); + assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false }); + assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true }); + assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen); + assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland); + assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string())); + assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen); + let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string())); + assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string())); + for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] { + assert!(!stays.xwayland(), "{stays:?}"); + } + assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland()); + } + + /// The pen check names the pen it found, for the log. + #[test] + fn the_pen_check_names_the_pen() { + assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen")); + let without = WITH_PEN.split("\n\n").take(2).collect::>().join("\n\n"); + assert_eq!(find_pen(&without), None); + assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line"); + } + /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the /// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests. const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\ diff --git a/assets/icons/dc-free-distort.svg b/assets/icons/dc-free-distort.svg index 9013cf97ae..3a6ea4451d 100644 --- a/assets/icons/dc-free-distort.svg +++ b/assets/icons/dc-free-distort.svg @@ -1,4 +1,4 @@ - + diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 92977884cf..820437c6ff 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -19,8 +19,11 @@ craft-affinity = { workspace = true } [dev-dependencies] proptest = { workspace = true } # The tests build containers and decode previews. -crc32fast = { workspace = true } craft-image-codecs = { workspace = true } # tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate # is tested without vectorcraft-engine (`cargo xtask ci shard`). vectorcraft-affinity = { path = ".", features = ["synth"] } + +# The files of other crates that this crate's tests compile or read, for CI's test selection. +[package.metadata.craft] +reads = ["xtask/affinity-corpus.sha256", "xtask/src/sha256.rs"] diff --git a/crates/affinity/tests/it/raster.rs b/crates/affinity/tests/it/raster.rs index 46e96c2013..2fac84f74b 100644 --- a/crates/affinity/tests/it/raster.rs +++ b/crates/affinity/tests/it/raster.rs @@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec { block.bytes(block.root, b"Data").unwrap().to_vec() } +/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for +/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK. +/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of +/// 0xFF, state 4 a stored tile (the next `Idx` entry), and any other state a tile of zeros. +fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec) { + const TILE: usize = 256; + let mut archive = Archive::open(bytes, Limits::default()).unwrap(); + let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap(); + // The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks. + let bitmaps: Vec = (0..doc.objects.len()) + .filter(|&o| doc.is(o, b"ImgN")) + .filter_map(|o| doc.obj(o, b"Bitm")) + .filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some()) + .collect(); + assert_eq!(bitmaps.len(), 1, "one tiled image bitmap"); + let bitmap = bitmaps[0]; + let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap(); + let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap(); + let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 { + 0 => (4, 1), + 1 => (4, 2), + 4 => (5, 1), + other => panic!("format {other}"), + }; + let row = width * bps; + let across = row.div_ceil(TILE); + let mut planes = Vec::new(); + for c in 1..=channels { + let digit = b'0' + c as u8; + let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") }; + let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter(); + let mut plane = vec![0u8; row * height]; + for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) { + let tile: Vec = match state { + stream::Value::UInt(2) => vec![0xFF; TILE * TILE], + stream::Value::UInt(4) => { + let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string(); + let data = archive.read(&name).unwrap(); + assert_eq!(data.len(), TILE * TILE, "{name}"); + data + } + _ => continue, + }; + let (ox, oy) = ((t % across) * TILE, (t / across) * TILE); + for y in oy..(oy + TILE).min(height) { + for x in ox..(ox + TILE).min(row) { + plane[y * row + x] = tile[(y - oy) * TILE + x - ox]; + } + } + } + planes.push(plane); + } + let sample = |c: usize, i: usize| -> u8 { + if bps == 1 { + planes[c][i] + } else { + let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]])); + u8::try_from((v * 255 + 32767) / 65535).unwrap() + } + }; + let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect(); + (u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels) +} + #[test] fn source_backed_tiles_retain_the_embedded_jpeg_pixels() { let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return }; @@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() { #[test] fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() { - let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return }; - let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap(); + let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return }; + let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap(); assert!(doc8.warnings.is_empty()); assert!(doc16.warnings.is_empty()); assert_eq!(images8.len(), 1); @@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() { assert_eq!(&pixels[..4], &[0, 0, 0, 128]); assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255)); assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1])); - // Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle. - assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1); + assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone())); + assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits"); } #[test] fn rotated_scaled_pixels_keep_the_full_affine_transform() { - let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return }; + let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return }; assert!(doc.warnings.is_empty()); assert_eq!(images.len(), 1); assert_eq!((images[0].width, images[0].height), (80, 60)); @@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() { let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() }; assert_eq!(pixels.len(), 80 * 60 * 4); assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)); - assert_eq!(crc32fast::hash(pixels), 0x3720a442); + assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone())); } #[test] fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() { // CMYK layers keep their inks for the importer to convert through a colour profile. - let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return }; + let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return }; assert_eq!(images.len(), 1); assert_eq!((images[0].width, images[0].height), (64, 48)); let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() }; assert_eq!(pixels.len(), 64 * 48 * 5); - assert_eq!(crc32fast::hash(pixels), 0x56b1f659); + assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone())); + assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels"); assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings); assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile"); let (_, lab, images) = read_fixture("patchy-lab.af").unwrap(); diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 79ed6df5ec..7afa67411f 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,33 +1,33 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] -affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] -patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] -patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] -patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"] -patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[] -patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[] -patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] -patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] -patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] -patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] -patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] -patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] -patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] -patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] -patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] -patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] -patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] -patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] -patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] -patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] +patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] +patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] +patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"] +patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[] +patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[] +patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] +patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] +patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] +patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] +patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] +patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] +patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] +patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] +patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] +patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] +patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] +patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] diff --git a/crates/affinity/tests/support/features.rs b/crates/affinity/tests/support/features.rs index f7024feb62..61eb43318b 100644 --- a/crates/affinity/tests/support/features.rs +++ b/crates/affinity/tests/support/features.rs @@ -1,8 +1,7 @@ //! Structural regression signatures, measured from the pinned files through our own reader. -//! These freeze feature retention; they are not independent visual or compatibility oracles. -//! The model CRC covers every decoded field via its Debug representation (including paths, -//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review; -//! input authenticity is independently checked with SHA256 by the corpus gate. +//! They count retained features; they are not independent visual or compatibility oracles. +//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked +//! with SHA256 by the corpus gate. use std::collections::{BTreeMap, BTreeSet}; use vectorcraft_affinity::model::{Document, Kind, Node}; use vectorcraft_affinity::paint::Paint; @@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String { for spread in &doc.spreads { visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1); } - let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes()); - format!( - "dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", - doc.dpi, - doc.spreads.len(), - doc.warnings - ) + format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings) } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index c5d13cd0fa..7abfb33a4e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() { } let (_, neutral_width) = start(neutral); let expected = 0.5 + x / 80.0; - assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); checked = true; } assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); @@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() { let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) }; bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width() }; - assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0)); + // Roundness 1% of the 10 pt size. + assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0)); assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0)); // The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°). let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) }; @@ -2219,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() { serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) ); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect(); + assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids"); + assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel)); + assert_eq!(Variation::parse("wheel"), None); assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } @@ -2227,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() { #[test] fn junk_pressure_brushes_draw_finite_art() { let bp = preview_path(120.0, 24.0); + let mut drawn = 0; for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] { for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] { let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile)); @@ -2235,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() { all_points(n, &mut pts); } assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}"); + drawn += usize::from(!pts.is_empty()); } } + assert_eq!(drawn, 12, "brushes that draw"); } /// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says. diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs index 9a350707a6..fdc31cb6cf 100644 --- a/crates/cad/src/hpgl/tests.rs +++ b/crates/cad/src/hpgl/tests.rs @@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() { let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); let widths: Vec = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); let want = [MM, 2.0 * MM, MM, 0.35 * MM]; - assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); + assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); } #[test] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dd80644279..16f4f97082 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; - assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); + // The red fill: its outline and its hatch. + assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]); } /// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it. @@ -1543,13 +1544,103 @@ fn export_bytes_match_shared_writer_goldens() { let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap(); let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF"); let path = dir.join(name); - if std::env::var_os("WRITE_DXF_GOLDENS").is_some() { - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(&path, got).unwrap(); - continue; - } let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); - assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); + assert_holds_shapes_doc(&expected, version); + if got != expected { + // Written for review only; a golden file changes by hand after its drawing checks pass. + let actual = std::env::temp_dir().join(format!("{name}.actual")); + let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display())); + panic!("DXF bytes changed versus {} (output {saved})", path.display()); + } + } +} + +/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt +/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and +/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and +/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter +/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4). +fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) { + let ents = section(&pairs(golden.as_bytes()), "ENTITIES"); + let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() }; + // Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE + // and HATCH headers, which no shape of the drawing reaches. + let points = |aci: &str| -> Vec<(f64, f64)> { + colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect() + }; + let bbox = |pts: &[(f64, f64)]| { + pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1))) + }; + for aci in ["1", "7"] { + let pts = points(aci); + assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}"); + assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}"); + // Each run of four points is one outline of the rectangle: all four corners, each joined to + // the next (and the last to the first) by a horizontal or vertical edge. + let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)]; + for quad in pts.chunks(4) { + assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}"); + for (i, a) in quad.iter().enumerate() { + let b = quad[(i + 1) % 4]; + assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}"); + } + } + } + let circle = colored("5"); + assert!(!circle.is_empty(), "{version:?}: the blue circle"); + if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") { + assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}"); + } else { + let pts = points("5"); + assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}"); + for (x, y) in &pts { + assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle"); + } + let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum(); + assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad"); + // Each segment, the closing one included, is an arc of the circle: the point halfway along it, + // which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too. + let mut verts: Vec<((f64, f64), f64)> = Vec::new(); + for e in &circle { + let mut x = None; + for (c, v) in e.iter() { + let n = || v.trim().parse::().expect("a number"); + match c { + 10 => x = Some(n()), + 20 => { + let p = (x.take().unwrap_or(f64::NAN), n()); + if p != (0.0, 0.0) { + verts.push((p, 0.0)); + } + } + 42 => { + if let Some(last) = verts.last_mut() { + last.1 = n(); + } + } + _ => {} + } + } + } + for (i, &((px, py), b)) in verts.iter().enumerate() { + let (qx, qy) = verts[(i + 1) % verts.len()].0; + let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0); + assert!( + ((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4, + "{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})" + ); + } + } + if version >= DxfVersion::R2000 { + let code = |aci: &str, c: i32| -> Vec { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() }; + assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color"); + assert_eq!(code("7", 420), ["0"], "{version:?}: black true color"); + assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color"); + assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke"); + assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke"); + } else { + let stroke = colored("7"); + assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width"); } } diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index c4338c289e..d622332c32 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -313,8 +313,10 @@ mod tests { assert_eq!(BlendMode::parse("ColorBurn"), Some(BlendMode::ColorBurn)); assert_eq!(BlendMode::parse("soft_light"), Some(BlendMode::SoftLight)); assert_eq!(BlendMode::parse("nope"), None); - for m in BlendMode::ALL { - assert_eq!(BlendMode::parse(m.label()), Some(m)); - } + assert_eq!(BlendMode::parse(""), None); + // A label that starts another one names its own mode. + assert_eq!(BlendMode::parse("Color"), Some(BlendMode::Color)); + assert_eq!(BlendMode::parse("Color Dodge"), Some(BlendMode::ColorDodge)); + assert_eq!(BlendMode::parse("HARD-LIGHT"), Some(BlendMode::HardLight)); } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 761a121191..47131dc678 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -15,11 +15,14 @@ fn de(a: [f32; 3], b: [f32; 3]) -> f32 { #[test] fn intents_parse_and_name() { - for i in Intent::ALL { - assert_eq!(Intent::parse(i.id()), Some(i)); - assert_eq!(Intent::parse(i.label()), Some(i)); - } + // The id settings save and the label the menu shows both read back, in any case and spacing. + assert_eq!(Intent::RelativeColorimetric.id(), "relative"); + assert_eq!(Intent::parse("relative"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("Relative Colorimetric"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("absolute_colorimetric"), Some(Intent::AbsoluteColorimetric)); + assert_eq!(Intent::parse("PERCEPTUAL"), Some(Intent::Perceptual)); assert_eq!(Intent::parse("bogus"), None); + assert_eq!(Intent::parse(""), None); } #[test] @@ -322,21 +325,29 @@ fn bad_icc_rejected() { assert!(matches!(register_icc(b"not a profile", None), Err(CmsError::BadProfile(_)))); } -#[cfg(target_os = "macos")] +/// A profile file is read and registered as its bytes are: a missing file is an I/O error naming +/// the path, a file that is not a profile is refused as one, and a file holding a built-in +/// profile is refused for its name. +#[cfg(not(target_arch = "wasm32"))] #[test] -fn loads_system_cmyk_icc() { - let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"); - if !path.exists() { - return; +fn loads_icc_files_and_refuses_bad_ones() { + let dir = std::env::temp_dir().join(format!("vectorcraft-color-icc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let missing = dir.join("missing.icc"); + match load_icc_file(&missing) { + Err(CmsError::Io(e)) => assert!(e.contains("missing.icc"), "{e}"), + other => panic!("{other:?}"), } - let info = load_icc_file(path).unwrap(); - assert_eq!(info.kind, ProfileKind::Cmyk); - assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin)); - let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap(); - let rgb = [0.7, 0.5, 0.4]; - let back = c.cmyk_to_srgb(c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric), false); - assert!(de(rgb, back) < 5.0, "{back:?}"); - assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]); + let junk = dir.join("junk.icc"); + std::fs::write(&junk, b"not a profile").unwrap(); + assert!(matches!(load_icc_file(&junk), Err(CmsError::BadProfile(_)))); + let builtin = dir.join("generic.icc"); + std::fs::write(&builtin, &*icc_bytes(GENERIC_CMYK).unwrap()).unwrap(); + match load_icc_file(&builtin) { + Err(CmsError::Unsupported(e)) => assert!(e.contains("built-in"), "{e}"), + other => panic!("{other:?}"), + } + std::fs::remove_dir_all(&dir).unwrap(); } /// With black-point compensation, sRGB black separates to the press's black point and that black @@ -568,10 +579,10 @@ fn a_document_gets_the_same_context_for_the_same_profiles() { /// settings saved before the policies existed read with the default policy. #[test] fn policies_parse_and_default_in_saved_settings() { - for p in Policy::CMYK { - assert_eq!(Policy::parse(p.id()), Some(p)); - } + assert_eq!(Policy::parse("preserveNumbers"), Some(Policy::PreserveNumbers)); + assert_eq!(Policy::parse("convert"), Some(Policy::Convert)); assert_eq!(Policy::parse("bogus"), None); + assert_eq!(Policy::parse("Preserve Numbers"), None, "only ids parse"); assert!(!Policy::RGB.contains(&Policy::PreserveNumbers)); let old: ColorSettings = serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 3506bcb856..8cefd7cfe5 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -395,5 +395,5 @@ fn cmyk_to_cmyk_compensates_the_black_point() { assert_ne!(convert(true), convert(false)); // White is untouched. let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap(); - assert!(white.iter().all(|v| *v < 0.01), "{white:?}"); + assert!(white.len() == 4 && white.iter().all(|v| *v < 0.01), "{white:?}"); } diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 7bf5735c7a..cd2e06a70e 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -108,6 +108,7 @@ fn the_fit_predicts_patches_it_left_out() { let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0); let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p)); + assert!(!left.is_empty(), "{}: nothing left out", c.reference); assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); let kept: Vec = kept.into_iter().copied().collect(); let left: Vec = left.into_iter().copied().collect(); diff --git a/crates/color/src/freeform.rs b/crates/color/src/freeform.rs index 11884d5c6c..9ea2af3e15 100644 --- a/crates/color/src/freeform.rs +++ b/crates/color/src/freeform.rs @@ -685,7 +685,9 @@ mod tests { let mid = f.split_line(0, 0, 0.5).unwrap(); assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2])); let p = f.points[3]; - assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}"); + // The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75 + // half way, not at the straight line's 50. + assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}"); assert!(f.remove_point(1)); assert_eq!(f.lines, vec![vec![0, 2, 1]]); assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err()); diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 5982e37552..0f520b2f9d 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -464,9 +464,10 @@ impl Gradient { self.repeats.clamp(1, MAX_REPEATS) } /// Does it paint something other than its end colors past the ends of its stops, or run its - /// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects? + /// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or + /// reflects? One without stops paints as one that pads. pub fn is_spread(&self) -> bool { - !self.spread.is_pad() && self.kind != GradientKind::Freeform + !self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty() } /// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever /// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs index ab088293da..c42b1acd61 100644 --- a/crates/color/src/gradient/spread/tests.rs +++ b/crates/color/src/gradient/spread/tests.rs @@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() { let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3); assert_eq!(free.spread_param(0.7), 0.7); assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread()); + // Without stops it paints as one that pads. + let empty = Gradient { stops: vec![], ..repeat.clone() }; + assert!(!empty.is_spread()); + assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1)); assert!(repeat.spread_param(f64::NAN).is_nan()); // A count out of range (set in code) counts as the nearest one in range. assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1); diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 25451aa3d7..fd39d0b94e 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -184,6 +184,7 @@ fn reverse_mirrors_midpoints() { r.reverse(); let mids: Vec = r.stops.iter().map(|s| s.midpoint).collect(); let want: Vec = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect(); + assert_eq!(mids.len(), g.stops.len(), "reversing keeps every stop"); assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}"); for i in 0..=20 { let t = i as f32 / 20.0; @@ -291,6 +292,7 @@ fn remove_keeps_two() { fn move_reorders_and_tracks_index() { let g = g3(); let (v, i) = move_stop(&g.stops, 0, 0.8); + assert_eq!(v.len(), g.stops.len(), "moving keeps every stop"); assert_eq!(i, 1); assert_eq!(v[1].color.to_hex(), "#ffffff"); assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset)); @@ -1176,7 +1178,8 @@ fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() { assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}"); assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}"); let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false); - assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}"); + assert_eq!(wedges.len(), 4, "{g:?}"); + assert!(wedges.iter().all(|(pts, _)| pts.len() >= 3 && pts.iter().all(|p| p.is_finite())), "{g:?}: {wedges:?}"); } // A flat extent keeps the vector's direction and the sign of its aspect. let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) }; @@ -1379,7 +1382,7 @@ fn diamond_pixels_follow_the_squares() { g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0)); let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect(); // White at the center, black in the corners, and the same on each side of it. - assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}"); + assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}"); assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]); assert_eq!(px[5 + 2], px[3 * 5 + 2]); assert_eq!(px[2 * 5 + 1], px[5 + 2]); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 58fcd886ee..75a5fdc2a5 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -177,20 +177,23 @@ mod tests { fn harmonies_keep_the_base_model() { let base = Color::cmyk(0.0, 1.0, 1.0, 0.0); for h in Harmony::ALL { - assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h)); + let colors = apply(h, base); + assert!(colors.len() >= 2 && colors.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}: {colors:?}", label(h)); } let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") }; assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}"); let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default()); - assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. }))); + let cells: Vec<&Color> = g.grid.iter().flatten().collect(); + assert!(!cells.is_empty() && cells.iter().all(|c| matches!(c, Color::Gray { .. })), "{cells:?}"); } #[test] fn rules_parse_by_id_and_label() { - for h in Harmony::ALL { - assert_eq!(parse(h.id()), Some(h)); - assert_eq!(parse(label(h)), Some(h)); - } + // A label reads back as its rule, its spaces and case ignored, and so does an id. + assert_eq!(parse("Split Complementary"), Some(Harmony::SplitComplementary)); + assert_eq!(parse("high contrast 3"), Some(Harmony::HighContrast3)); + assert_eq!(parse("tetrad2"), Some(Harmony::Tetrad2)); + assert_eq!(parse(""), None); assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index b4197ca0ef..f7e482e567 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -825,16 +825,4 @@ mod tests { let [l, ..] = to_oklab(&stop("Violet Edge", 4)); assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}"); } - - #[test] - fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() { - for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) { - for s in builtin_library(b.id).unwrap().iter() { - if let Paint::Gradient(g) = &s.paint { - assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name); - assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name); - } - } - } - } } diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 05c386e405..c90257b9f1 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -796,12 +796,12 @@ mod tests { #[test] fn methods_parse_by_id_and_label() { - for m in Method::ALL { - assert_eq!(Method::parse(m.id()), Some(m)); - assert_eq!(Method::parse(m.label()), Some(m)); - } + assert_eq!(Method::parse("preserveTints"), Some(Method::PreserveTints)); + assert_eq!(Method::parse("Hue Shift"), Some(Method::HueShift)); + assert_eq!(Method::parse("Tints and Shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("nope"), None); + assert_eq!(Method::parse(""), None); } #[test] diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index 12ae31220a..b9ce45b1df 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -186,13 +186,20 @@ mod tests { #[test] fn default_swatches_parse() { - // `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure - // none falls back. - let src = include_str!("swatch.rs"); - let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect(); - assert!(hexes.len() > 30); - for h in hexes { - assert!(Color::from_hex(h).is_some(), "{h}"); - } + // `solid` and `grad` fall back to black or white on a bad hex literal. A fallback gives a + // solid the color of Black or White, and a gradient a stop that differs from the swatch + // its hex literal names. + let (s, g) = default_swatches(Model::Rgb); + let solids: Vec = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).filter_map(|w| w.paint.color()).collect(); + assert!(solids.len() > 40, "{}", solids.len()); + let repeated: Vec<&Color> = solids.iter().enumerate().filter(|(i, c)| solids[..*i].contains(c)).map(|(_, c)| c).collect(); + assert_eq!(repeated, Vec::<&Color>::new(), "colors of more than one default swatch"); + let color = |name: &str| s.iter().find(|w| w.name == name).and_then(|w| w.paint.color()); + let stops = |name: &str| match s.iter().find(|w| w.name == name).map(|w| &w.paint) { + Some(Paint::Gradient(gp)) => gp.gradient.stops.iter().map(|st| Some(st.color)).collect::>(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!(stops("Sunset"), [color("Amber"), color("Rose")]); + assert_eq!(stops("Ocean"), [color("Cyan"), color("Blue")]); } } diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ba5bb3b974..9abb0d80ea 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -208,10 +208,11 @@ mod tests { #[test] fn category_ids_parse_back() { - for c in Category::ALL { - assert_eq!(Category::parse(c.id()), Some(c)); - } + // Commands and saved settings name a category by its id, exactly. + assert_eq!(Category::parse("largeText"), Some(Category::LargeText)); + assert_eq!(Category::parse("graphics"), Some(Category::Graphics)); assert_eq!(Category::parse("NormalText"), None); + assert_eq!(Category::parse("Large Text"), None, "a label is not an id"); } fn hue(srgb: [f32; 3]) -> f64 { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 2770471f70..7c40d9d133 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2784,10 +2784,13 @@ mod tests { Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) }; let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); } @@ -2840,6 +2843,7 @@ mod tests { let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]); let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]); let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2848,6 +2852,7 @@ mod tests { // Without plates on either side the steps print the spot ink alone, as before. let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]); let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -2882,10 +2887,12 @@ mod tests { let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]); let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05])); // The ends keep their own plates. let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); // Another swatch, or an unlinked stop: process steps with no plates, as before. @@ -2897,6 +2904,7 @@ mod tests { let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]); for b in [&other, &plain] { let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } } @@ -2906,11 +2914,14 @@ mod tests { let p = [0.4, 0.8, 0.0, 0.2]; let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let Paint::Gradient(g) = &gradient else { panic!() }; - assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none())); + let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient); + assert_eq!(linked.stops.len(), 2); + assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops); let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 }; // The solid's end has no plates: they grow from none toward the gradient's, both ways round. for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] { let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2919,6 +2930,7 @@ mod tests { } // A process solid unlinks the steps, and they take no plates. let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -3401,7 +3413,8 @@ mod tests { #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); - assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + // Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it. + assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]); } #[test] @@ -3412,7 +3425,8 @@ mod tests { let mid = lerp_node(&a, &b, 0.4); let mut ids = vec![]; mid.walk(&mut |n| ids.push(n.id)); - assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}"); + // The step and its two members, all of them new. + assert_eq!(ids, [NodeId(0); 3]); } /// A blend of `a` and `b` spaced by `spacing`. diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs index 3b36ff86dd..f3f4b83939 100644 --- a/crates/doc/src/compound_shape.rs +++ b/crates/doc/src/compound_shape.rs @@ -64,11 +64,10 @@ mod tests { #[test] fn modes_read_back_and_unknown_ones_are_add() { - for m in ShapeMode::ALL { - let v = serde_json::to_value(m).unwrap(); - assert_eq!(v, serde_json::json!(m.name())); - assert_eq!(serde_json::from_value::(v).unwrap(), m); - } + assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract")); + assert_eq!(serde_json::from_value::(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude); + assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect)); + assert_eq!(ShapeMode::parse("Intersect"), None); for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { assert_eq!(serde_json::from_value::(v).unwrap(), ShapeMode::Add); } diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index c846dfc1c6..3872e16a54 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -613,6 +613,7 @@ mod tests { d.limit_depth_noting(&mut warnings); assert_eq!(warnings, [symbols_note()]); assert!(!d.too_deep(None), "{count} {last}"); + assert_eq!(d.symbols.len(), count, "every symbol is kept"); assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group"); } // An edit that makes one hold itself is seen, whatever else stayed as it was. diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 537a1d6e60..8a5c4e24fb 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -394,9 +394,11 @@ pub enum DimensionSource { /// it is vertical. Versions without this source do not open the file. Extent { node: NodeId, - /// Placed with Use Preview Bounds on: the points are moved out to the outside of the - /// strokes the path paints ([`preview_extents`]), the width or height that W and H show. - /// Versions without it measure between the outermost points themselves. + /// The points are moved out to the outside of the strokes the path paints + /// ([`preview_extents`]), the width or height that W and H show with Use Preview Bounds on. + /// The Dimension tool sets it on every dimension of a whole path it places. Without it, + /// as in files saved before the tool set it and in versions without it, the dimension + /// measures between the outermost points themselves. #[serde(default, skip_serializing_if = "std::ops::Not::not")] preview: bool, }, @@ -431,9 +433,9 @@ impl DimensionSource { } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. /// A node without a path, or missing from both, counts as changed. For a dimension of a whole - /// path placed with Use Preview Bounds on, so does a change to the strokes the path paints - /// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw - /// on it, and the path being made into a guide or released from one. + /// path measured to the outside of its strokes (`preview`), so does a change to the strokes the + /// path paints ([`stroked_by`]): their appearance, the node they come from, or which arrowheads + /// they draw on it, and the path being made into a guide or released from one. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { let strokes = matches!(self, Self::Extent { preview: true, .. }); self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 36fe29a8f2..43614eba87 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -108,6 +108,7 @@ impl GraphDesign { let mut e = n.extras_mut(); e.graph = None; e.series_index = None; + e.graph_design_art = false; } if let Some(ch) = n.children_mut() { let old = std::mem::take(ch); diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index 8f514a3b71..f5b087125d 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -457,7 +457,7 @@ mod tests { n.transform(Affine::scale_non_uniform(1.0, 0.25), false); assert!(n.extras().image_quad.is_none()); let b = n.geometric_bounds().unwrap(); - assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}"); + assert!(b.height() < 1e-6 && (b.x0 + 200.0 / 9.0).abs() < 1e-6 && (b.x1 - 1400.0 / 9.0).abs() < 1e-6, "{b:?}"); } /// A file's corners that the image cannot take are dropped as it is read, so a later scale diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 9dbb409706..99ca99a2c5 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -22,6 +22,8 @@ pub struct NodeExtras { /// Index of the graph series this generated group belongs to. Axes, the legend and other /// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them. pub series_index: Option, + /// This object is a generated copy of a graph column or marker design. + pub graph_design_art: bool, /// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale /// the placed gradients in it with the outlines. pub type_outlines: bool, @@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { wrap: None, graph: None, series_index: None, + graph_design_art: false, type_outlines: false, pixelated: false, shaper: None, diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index ed2fdb08d9..480e201e2d 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() { e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true))); e.trace = Some(Box::new(serde_json::json!({"preset": "p"}))); e.series_index = Some(2); + e.graph_design_art = true; e.type_outlines = true; e.graphic_style = Some(3); e.attrs = Some(Box::default()); @@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() { "mask", "trace", "series_index", + "graph_design_art", "type_outlines", "kind", "graphic_style", diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index d543c9d9e1..234adb7793 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -36,6 +36,7 @@ impl Serialize for Node { e.wrap.is_none(), e.graph.is_none(), e.series_index.is_none(), + is_default(&e.graph_design_art), is_default(&e.type_outlines), is_default(&e.pixelated), e.shaper.is_none(), @@ -86,6 +87,7 @@ impl Serialize for Node { field!("wrap", &e.wrap); field!("graph", &e.graph); field!("series_index", &e.series_index); + field!("graph_design_art", &e.graph_design_art); field!("type_outlines", &e.type_outlines); field!("pixelated", &e.pixelated); field!("shaper", &e.shaper); @@ -220,6 +222,8 @@ pub(super) struct NodeWire { #[serde(default)] series_index: Option, #[serde(default)] + graph_design_art: bool, + #[serde(default)] type_outlines: bool, #[serde(default)] pixelated: bool, @@ -480,6 +484,7 @@ impl From for Node { wrap: w.wrap, graph: w.graph, series_index: w.series_index, + graph_design_art: w.graph_design_art, type_outlines: w.type_outlines, pixelated: w.pixelated, shaper: w.shaper, diff --git a/crates/doc/src/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs index 241c61fba8..d9017815c7 100644 --- a/crates/doc/src/symbol_overrides.rs +++ b/crates/doc/src/symbol_overrides.rs @@ -253,6 +253,7 @@ mod tests { let mut a = Node::group(NodeId(1), vec![Arc::new(text)]); apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]); let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") }; + assert_eq!(t.runs.len(), 1); assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt"); // A path whose stroke has neither paint nor weight gets 1 pt too. diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..607fa12238 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() { assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); } assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); - for d in Digits::ALL { - assert_eq!(serde_json::to_value(d).unwrap(), d.id()); - assert_eq!(serde_json::from_value::(d.id().into()).unwrap(), d); - assert_eq!(Digits::from_id(d.id()), Some(d)); - } + assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari"); + assert_eq!(serde_json::from_value::("farsi".into()).unwrap(), Digits::Farsi); + assert_eq!(Digits::Malayalam.id(), "malayalam"); + assert_eq!(Digits::from_id("default"), Some(Digits::Default)); assert_eq!(Digits::from_id("roman"), None); assert!(serde_json::from_value::("roman".into()).is_err()); } diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..f462e18300 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -98,11 +98,10 @@ mod tests { #[test] fn ids_round_trip_and_unknown_views_show_the_result() { - for v in TraceView::ALL { - assert_eq!(TraceView::from_id(v.id()), Some(v)); - assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v)); - assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something"); - } + assert_eq!(TraceView::Source.id(), "sourceImage"); + assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource)); + assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter"); + assert_eq!(TraceView::from_id("tracing"), None); let mut g = Node::group(crate::NodeId(1), vec![]); assert_eq!(g.trace_view(), TraceView::Result); g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"}))); diff --git a/crates/effects/src/addons/color.rs b/crates/effects/src/addons/color.rs index 07627dd8d7..3cb72f60d4 100644 --- a/crates/effects/src/addons/color.rs +++ b/crates/effects/src/addons/color.rs @@ -109,10 +109,9 @@ mod tests { #[test] fn the_effects_are_colour_adjustments_in_their_own_menu() { - for id in EFFECTS { - assert!(crate::is_adjustment(id), "{id}"); - assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]); - } + assert!(crate::is_adjustment(DUOTONE)); + assert_eq!(crate::effect_info(DUOTONE).unwrap().menu, ["Effect", "Color Effects"]); + assert!(!crate::is_adjustment("stylize.dropShadow"), "an effect outside the add-on is not one"); } #[test] @@ -122,8 +121,12 @@ mod tests { // One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686. assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3])); assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3])); - assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows"); - assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6); + // The offset adds linear light: linear 0.1 is sRGB 0.349. + let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]); + assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}"); + // Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710. + let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey); + assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}"); assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped"); } diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 9b5771e7bd..d371bfb363 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes}; use vectorcraft_pathops::{self as po, BoolOp}; use crate::catalog::{EffectInfo, Lengths}; @@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), @@ -63,6 +63,12 @@ pub enum DotShape { Square, Diamond, Line, + /// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then + /// round holes, as the Euclidean spot function draws them. + Euclidean, + /// Elongated dots that join along their long side at 40% into chains, along their short side + /// at 60%, then elongated holes. + Elliptical, } impl DotShape { @@ -73,6 +79,8 @@ impl DotShape { "square" => DotShape::Square, "diamond" => DotShape::Diamond, "line" | "lines" => DotShape::Line, + "euclidean" => DotShape::Euclidean, + "elliptical" => DotShape::Elliptical, _ => return None, }) } @@ -82,22 +90,345 @@ impl DotShape { fn path(self, t: f64, s: f64) -> PathData { let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); match self { - DotShape::Circle => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r))) - } - DotShape::Ellipse => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3))) - } + DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), + DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), DotShape::Square => square(s * t.sqrt()), - DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), + DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), + DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)), + DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)), } } } +/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it +/// (π × ratio / 4 = 0.4 of a quadrant). +const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI; + +/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line +/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y +/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own +/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%. +const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75); + +/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5. +const SIZE_STEPS: usize = 512; + +static EUCLIDEAN: OnceLock> = OnceLock::new(); +static ELLIPTICAL: OnceLock> = OnceLock::new(); + +/// The two spot-function dots. +#[derive(Clone, Copy)] +enum SpotKind { + Euclidean, + Elliptical, +} + +impl SpotKind { + /// The first quadrant of the dot of width `a` in a quadrant of half side 1. + fn quadrant(self, a: f64) -> Vec { + match self { + SpotKind::Euclidean => quadrant(a, a, 1.0), + SpotKind::Elliptical => elliptical_quadrant(a), + } + } + + /// The width at which the dot covers half the cell. + fn max_size(self) -> f64 { + match self { + SpotKind::Euclidean => 1.0, + SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + SpotKind::Euclidean => &EUCLIDEAN, + SpotKind::Elliptical => &ELLIPTICAL, + } + } +} + +/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the +/// cell [-1, 1]². +fn dot_sizes(kind: SpotKind) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + // A quadrant of the cell has area 1. + let target = k as f64 / SIZE_STEPS as f64 * 0.5; + let (mut lo, mut hi) = (0.0, kind.max_size()); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() +} + +/// The area between the origin and `curves`, which run from the x axis to the y axis. +fn curves_area(curves: &[CubicBez]) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArea; + curves.iter().map(|c| c.signed_area()).sum() +} + +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { + if t1 <= t0 { + return; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let d = (t1 - t0) / n; + let k = 4.0 / 3.0 * (d / 4.0).tan(); + for i in 0..n as usize { + let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); + let (p0, p3) = (at(u0), at(u1)); + let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); + let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); + out.push(CubicBez::new(p0, c1, c2, p3)); + } +} + +/// The straight segment from `p` to `q` as a cubic curve. +fn segment(p: Point, q: Point) -> CubicBez { + CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q) +} + +/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a +/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole +/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot +/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side. +fn elliptical_quadrant(a: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let b = a * ELLIPTICAL_RATIO; + let mut out = vec![]; + if a <= 1.0 { + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); + return out; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let (m, c) = ELLIPTICAL_CUT; + // The ellipse crosses the side x = 1 at angle t0. + let t0 = (1.0 / a).acos(); + // Between angles ts and te the ellipse lies beyond the cut line. + let r = (m * a).hypot(b); + let (ts, te) = if r > c { + let (phi, alpha) = (b.atan2(m * a), (c / r).acos()); + (phi - alpha, phi + alpha) + } else { + (FRAC_PI_2, FRAC_PI_2) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) }; + out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) })); + if t0 >= te { + ellipse_arc(&mut out, a, b, t0, FRAC_PI_2); + return out; + } + if t0 < ts { + ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2)); + if ts >= FRAC_PI_2 { + return out; + } + } + let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3); + out.push(segment(from, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); + out +} + +/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤ +/// `h`, from its point on the x axis to its point on the y axis, as cubic curves. +fn quadrant(a: f64, b: f64, h: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let mut out = vec![]; + let r = a.hypot(b); + if r <= h { + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); + return out; + } + let (phi, alpha) = (b.atan2(a), (h / r).acos()); + let (ts, te) = (phi - alpha, phi + alpha); + let start = if ts > 0.0 { + ellipse_arc(&mut out, a, b, 0.0, ts); + at(ts) + } else { + Point::new(h, 0.0) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) }; + out.push(segment(start, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); + out +} + +/// `curves` reversed, each curve run backwards. +fn reversed(curves: &[CubicBez]) -> Vec { + curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect() +} + +/// `curves` with each point mapped by `f`. +fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec { + curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect() +} + +/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from +/// the kind's table ([`dot_sizes`]). +fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec { + let sizes = kind.table().get_or_init(|| dot_sizes(kind)); + let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let a = lo + (hi - lo) * (x - i as f64); + mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h)) +} + +/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to +/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's +/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half, +/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the +/// light becomes holes. +fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { + if t <= 0.5 { + return four_quadrants(&spot_quadrant(t, h, kind)); + } + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + // Round the corners counterclockwise, each one's hole the dot of the opposite tone. + let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + bp.close_path(); + bp +} + +/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along +/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole +/// cell at full tone. +#[derive(Clone, Copy)] +enum CellKind { + Circle, + /// 1.69 times as wide as tall. + Ellipse, + Diamond, +} + +static CELL_CIRCLE: OnceLock> = OnceLock::new(); +static CELL_ELLIPSE: OnceLock> = OnceLock::new(); +static CELL_DIAMOND: OnceLock> = OnceLock::new(); + +impl CellKind { + /// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to + /// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half + /// diagonal `r`. + fn quadrant(self, r: f64) -> Vec { + let corner = Point::new(1.0, 1.0); + match self { + CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))], + CellKind::Diamond if r < 2.0 => vec![ + segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)), + segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)), + segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)), + ], + CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))], + CellKind::Circle | CellKind::Ellipse => { + let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + // The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty. + let tx = (1.0 / a).min(1.0).acos(); + let ty = (1.0 / b).min(1.0).asin(); + if tx >= ty { + return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))]; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let mut out = vec![]; + if a > 1.0 { + out.push(segment(Point::new(1.0, 0.0), at(tx))); + } + ellipse_arc(&mut out, a, b, tx, ty); + if b > 1.0 { + out.push(segment(at(ty), Point::new(0.0, 1.0))); + } + out + } + } + } + + /// The size at which the dot covers the whole quadrant. + fn max_size(self) -> f64 { + match self { + CellKind::Circle => std::f64::consts::SQRT_2, + // 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner. + CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(), + CellKind::Diamond => 2.0, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + CellKind::Circle => &CELL_CIRCLE, + CellKind::Ellipse => &CELL_ELLIPSE, + CellKind::Diamond => &CELL_DIAMOND, + } + } + + /// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone. + fn sizes(self) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + let target = k as f64 / SIZE_STEPS as f64; + let (mut lo, mut hi) = (0.0, self.max_size()); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() + } +} + +/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to +/// the cell ([`CellKind`]). +fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { + let sizes = kind.table().get_or_init(|| kind.sizes()); + let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let r = lo + (hi - lo) * (x - i as f64); + let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h)); + PathData::from_bezpath(&four_quadrants(&q1)) +} + +/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other +/// three quadrants, counterclockwise. +fn four_quadrants(q1: &[CubicBez]) -> BezPath { + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + add(q1.to_vec(), true); + add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false); + add(mapped(q1, |p| Point::new(-p.x, -p.y)), false); + add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false); + bp.close_path(); + bp +} + /// One screen: its ink and angle, and how to read its tone from a sampled pixel. struct Screen { paint: Color, @@ -399,6 +730,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option { mod tests { use super::*; use vectorcraft_doc::Effect; + use vectorcraft_geom::Shape; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -464,6 +796,91 @@ mod tests { assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2); } + /// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`? + fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool { + fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) + } + + #[test] + fn spot_dots_cover_the_tone() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + for k in 1..100 { + let t = f64::from(k) / 100.0; + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + } + } + assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); + } + + #[test] + fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] { + for t in [0.2, 0.6, 0.85, 0.97] { + // The dot never reaches into a neighbor's cell, so dots of different tones meet + // along the shared side instead of overlapping into notches. + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + // What it covers of the cell is the tone. + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + } + // Full tone is the whole cell, its corners included. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}"); + assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}"); + } + } + + #[test] + fn euclidean_dots_meet_corner_to_corner_at_half() { + let s = DotShape::Euclidean; + // Round dots apart from their neighbors below half. + assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0))); + // At half the dot is the diamond reaching the middle of each side: a checkerboard. + for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] { + assert!(covers(s, 0.5, p), "{p:?}"); + } + assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24))); + // Past half the light becomes round holes at the corners. + assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49))); + assert!(covers(s, 0.99, (0.3, 0.3))); + } + + #[test] + fn elliptical_dots_join_along_their_length_then_their_width() { + let s = DotShape::Elliptical; + // Below 40% the dots stand apart. + assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45))); + // From 40% they reach their neighbors along x, making chains, but not along y. + assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45))); + // The chains are bridges as tall as the tone allows across the shared side, not single + // points: off the axis on the side x = 0.5, and on the cell's other side by symmetry. + assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2))); + assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49))); + // Up to 60% the light still runs along the top edge between the corner holes. + assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3))); + // Past 60% the dark joins across the top edge too, leaving elongated holes. + assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49))); + // The holes are longer along x than along y. + assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}"); + // Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall. + let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap(); + assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}"); + } + + #[test] + fn spot_shapes_make_dots_through_the_screen() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap(); + assert_eq!(h.shape, shape); + let (s, b) = black_square(60.0, &h); + let (layers, dots) = h.layers(&s, b, None); + assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}"); + } + } + #[test] fn the_caps_refuse_too_many_cells() { let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap(); diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 5c31278493..474a6c0a0c 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -744,7 +744,7 @@ pub fn effect_catalog() -> Vec { "pixelate.colorHalftone", "Color Halftone…", PIXELATE, - "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} The effect screens cyan, magenta and yellow ink (channels 1 to 3; CMYK mode adds black as channel 4) at their angles into dots whose area follows the cell's mean ink coverage.", json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), ), r( diff --git a/crates/effects/src/pixel/pixelate.rs b/crates/effects/src/pixel/pixelate.rs index 0318eb5f45..e7fcf05e08 100644 --- a/crates/effects/src/pixel/pixelate.rs +++ b/crates/effects/src/pixel/pixelate.rs @@ -437,7 +437,7 @@ impl Screen { /// Color Halftone: each channel screened at its angle in square cells sized so that a dot of /// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's -/// dot covers the share of it that is the channel's mean there (white stays white, black black). +/// dot covers the mean ink coverage of that cell (white stays white, black black). /// Coverage stays as it is. pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) { let Some(place) = Place::new(space, w, h) else { return }; @@ -446,7 +446,8 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix if !(side.is_finite() && side / place.px >= 3.0) { return; } - let channels = space.channels; + // Screen RGB as dark ink against white, like the CMY channel previews. + let channels = if space.channels == Channels::Rgb { Channels::CmyPlane } else { space.channels }; let n = split([0; 4], channels).1; let limit = w.saturating_mul(h).saturating_add(4096); let mut screens = Vec::with_capacity(n); @@ -478,7 +479,7 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 }; // Full strength fills the cell, corners too; none leaves no speck. let radius = match mean { - m if m >= 254.5 / 255.0 => f64::INFINITY, + m if m >= 254.5 / 255.0 => side / std::f64::consts::SQRT_2 + 0.5 * place.px, m if m <= 0.5 / 255.0 => 0.0, m => dot_radius(m) * side, }; diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 6dd7942e5e..f389c399e7 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() { assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100"); } -/// FNV-1a of `bytes`. -fn digest(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) -} - #[test] fn smart_blur_normal_mode_keeps_its_pixels() { let (w, h) = (48, 40); @@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() { let a = if x > 4 && y < 36 { 255 } else { 128 }; [((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a] }); - let mut sums = Vec::new(); for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] { let mut d = src.clone(); fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h)); @@ -715,10 +709,127 @@ fn smart_blur_normal_mode_keeps_its_pixels() { p["blurMode"] = json!("normal"); fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h)); assert_eq!(d, normal); - sums.push(digest(&d)); } - // The pixels Smart Blur gave before it had a mode. - assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]); +} + +/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included, +/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110 +/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither +/// takes the other. +#[test] +fn smart_blur_averages_only_the_neighbours_within_the_threshold() { + let (w, h) = (5, 1); + let src = image(w, h, |x, _| match x { + 0 => [100, 100, 100, 255], + 1 => [110, 110, 110, 255], + 2 => [200, 200, 200, 255], + 3 => [100, 100, 100, 255], + _ => [100, 100, 100, 128], + }); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]); + assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]); + assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]); + assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0)); + assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0)); +} + +/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray +/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark +/// side of the step takes in some lighter gray and the pixel on the light side some darker gray, +/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of +/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray. +#[test] +fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() { + let (w, h) = (60, 40); + let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 })); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h)); + let dark = at(&d, w, 29, 20)[0]; + let light = at(&d, w, 30, 20)[0]; + assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}"); + assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}"); + assert_eq!(at(&d, w, 10, 20), grey(100)); + assert_eq!(at(&d, w, 50, 20), grey(200)); + // Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead + // of 3, so less of the other gray reaches the pixels next to the step. + let mut medium = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h)); + let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]); + assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}"); + assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}"); + // At threshold 30 the blurred values next to the step are too far from both grays, and the + // pixels on either side keep their gray. + let mut sharp = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h)); + assert_eq!(at(&sharp, w, 29, 20), grey(100)); + assert_eq!(at(&sharp, w, 30, 20), grey(200)); +} + +/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis, +/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100 +/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the +/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100. +/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100. +/// Including them would average ten samples of 100 with three of about 114.29 and round to 103. +#[test] +fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() { + let (w, h) = (60, 40); + let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 })); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 24, 20), grey(100)); +} + +/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels +/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210 +/// average to 205, and 60 is too far from both groups and stays. +#[test] +fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() { + let (w, h) = (6, 1); + let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x])); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h)); + let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x])); + assert_eq!(d, want); +} + +/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5. +/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200, +/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages +/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is +/// excluded and the center stays 100. Reading the whole square would give 110 in both cases. +#[test] +fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() { + let (w, h) = (5, 5); + for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] { + let src = image(w, h, |x, y| match (x, y) { + (2, 2) => grey(100), + p if p == (nx, ny) => grey(120), + _ => grey(200), + }); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})"); + } +} + +/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset +/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5. +/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are +/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110. +/// A search limited to two pixels would leave the center at 100. +#[test] +fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() { + let (w, h) = (7, 7); + let mut d = image(w, h, |x, y| match (x, y) { + (3, 3) => grey(100), + (6, 3) => grey(120), + _ => grey(200), + }); + fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 3, 3), grey(110)); } /// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6 @@ -954,60 +1065,6 @@ fn linear_light_blur_mixes_light_not_values() { } } -/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored -/// --nocapture pixel_timings`). -#[test] -#[ignore] -fn pixel_timings() { - let (w, h) = (2000, 2000); - let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]); - let s = PixelSpace { - to_doc: Affine::IDENTITY, - px: 1.0, - center: Point::new(1000.0, 1000.0), - size: vectorcraft_geom::Vec2::new(2000.0, 2000.0), - channels: Channels::Rgb, - line: 1.0, - extent: 0.0, - }; - let cases = [ - ("blur.radial", json!({"quality": "draft"})), - ("blur.radial", json!({"quality": "good"})), - ("blur.radial", json!({"quality": "best", "method": "zoom"})), - ("blur.smart", json!({"quality": "low"})), - ("blur.smart", json!({"quality": "high", "radius": 30})), - ("sharpen.unsharpMask", json!({"radius": 20})), - ("brushStrokes.accentedEdges", json!({"edgeWidth": 14})), - ("brushStrokes.angledStrokes", json!({"strokeLength": 50})), - ("brushStrokes.crosshatch", json!({"strokeLength": 50, "strength": 3})), - ("brushStrokes.darkStrokes", json!({})), - ("brushStrokes.inkOutlines", json!({"strokeLength": 50})), - ("brushStrokes.spatter", json!({"sprayRadius": 25})), - ("brushStrokes.sprayedStrokes", json!({"strokeLength": 20, "sprayRadius": 25})), - ("brushStrokes.sumiE", json!({"strokeWidth": 15})), - ("pixelate.colorHalftone", json!({"maxRadius": 4})), - ("pixelate.crystallize", json!({"cellSize": 3})), - ("pixelate.crystallize", json!({"cellSize": 300})), - ("pixelate.mezzotint", json!({"type": "grainyDots"})), - ("pixelate.pointillize", json!({"cellSize": 3})), - ("pixelate.pointillize", json!({"cellSize": 300})), - ("texture.craquelure", json!({"crackSpacing": 2})), - ("texture.craquelure", json!({"crackSpacing": 100})), - ("texture.grain", json!({"grainType": "clumped"})), - ("texture.mosaicTiles", json!({"tileSize": 2})), - ("texture.patchwork", json!({"squareSize": 0})), - ("texture.stainedGlass", json!({"cellSize": 2})), - ("texture.texturizer", json!({"texture": "sandstone", "scaling": 50})), - ("texture.texturizer", json!({"texture": "burlap"})), - ]; - for (id, p) in cases { - let mut d = src.clone(); - let t = std::time::Instant::now(); - fx(id, p.clone()).apply(&mut d, w, h, &s); - println!("{id} {p}: {:?}", t.elapsed()); - } -} - #[test] fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] }); @@ -1070,13 +1127,44 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() { let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] }); halftone.apply(&mut half, w, h, &space(w, h)); assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4]))); - // Dots are bigger where the image is brighter. + // Brighter areas have fewer dark pixels. let mut ramp = image(w, h, |x, _| grey((x * 4) as u8)); halftone.apply(&mut ramp, w, h, &space(w, h)); let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count(); assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40)); } +#[test] +fn color_halftone_draws_dark_dots_on_light_rgb() { + let (w, h) = (64, 64); + let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})); + let mut d = image(w, h, |_, _| grey(192)); + halftone.apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 37, 37), grey(0)); + assert_eq!(at(&d, w, 32, 32), grey(255)); +} + +#[test] +fn color_halftone_full_coverage_only_overlaps_the_edge_of_an_empty_neighbor() { + let (w, h) = (96, 64); + let source = image(w, h, |x, _| grey(if x < w / 2 { 0 } else { 255 })); + let mut screened = source.clone(); + fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})).apply(&mut screened, w, h, &space(w, h)); + let half_cell = (8.0 * std::f64::consts::SQRT_2 / 2.0) as usize; + let (edge, y) = (w / 2, h / 2 + half_cell); + assert_eq!(at(&screened, w, edge - half_cell, y), grey(0), "the full cell keeps its center"); + assert_eq!(at(&screened, w, edge, y), grey(0), "the round dot crosses the straight cell edge"); + let fringe = at(&screened, w, edge + 2, y)[0]; + assert!(fringe > 0 && fringe < 255, "the last overlapping column is antialiased: {fringe}"); + // With an 8 px radius and the grid aligned to this edge, the circle and its antialiasing + // can reach only the first three columns of white. Check every row, including cell corners. + for y in 0..h { + for x in edge + 3..w { + assert_eq!(at(&screened, w, x, y), grey(255), "unexpected ink at ({x}, {y})"); + } + } +} + #[test] fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() { // Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ef1608a5d9..83bb1ca9f7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -600,9 +600,9 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { } let (parts, bounds) = solid_parts(shapes, b); if !cast { - return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); + return built_solids(id, p, &parts, bounds, object_face_limit()).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None) + let built = built_solids_cast(id, p, &parts, bounds, object_face_limit(), true, false, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -1025,13 +1025,30 @@ thread_local! { /// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow /// ([`cast_shadow`]) count too. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The limit [`object_face_limit`] gives on this thread: [`MAX_OBJECT_FACES`] unless a test sets + /// a lower one, so that a test of the limit builds small solids. + pub(crate) static OBJECT_FACE_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_OBJECT_FACES) }; +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`]. +#[cfg(not(test))] +fn object_face_limit() -> usize { + MAX_OBJECT_FACES +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`], or the lower limit a test set in [`OBJECT_FACE_LIMIT`]. +#[cfg(test)] +fn object_face_limit() -> usize { + OBJECT_FACE_LIMIT.with(std::cell::Cell::get) } /// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from /// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as /// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its /// faces not counted); a fill's is an error. The faces of the solids kept count together: once they -/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and +/// pass `limit` ([`object_face_limit`] for the art) the result is an error, and /// no later part is built. An error ends the iterator. fn built_solids<'a>( id: &'a str, @@ -1211,7 +1228,7 @@ fn rects_overlap(a: Rect, b: Rect) -> bool { /// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces /// and whose paint copies take `paint_bytes` so far: as many as keep the faces within -/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as +/// [`object_face_limit`] and the copies within the allowance, each added face counted as /// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint. fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { let per_face = items @@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator, faces: usize, p .unwrap_or(0) .max(1); let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; - MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) + object_face_limit().saturating_sub(faces).min(affordable) } /// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a @@ -2403,7 +2420,7 @@ fn surfaces_with( let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); let mut layouts: Vec = vec![]; let mut surfaces_before = 0usize; - let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); + let made = built_solids_cast(&fx.id, &p, &parts, bounds, object_face_limit(), cast, membrane, carrier); for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; let layout = map_art.as_ref().map(|_| { @@ -2471,7 +2488,7 @@ fn surfaces_with( if solids.iter().any(|s| ordered(s.4)) { // A stroke face that passes through a fill wall or another stroke's face is cut where it // does. The pieces count against the limits as the faces did: cutting stops before the - // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // faces pass object_face_limit() or their paint copies pass the allowance, so an effect that // draws uncut still draws. let counts: Vec = solids.iter().map(|(.., f, _)| f.len()).collect(); let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); @@ -2940,7 +2957,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' // their handles. A stroke left out places none of its own. When a fill's solid can't be // built, or the solids together pass the limit, the art draws its source and no piece // places a handle. - let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None) + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None) .collect::, String>>() .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) .unwrap_or_default(); @@ -3065,7 +3082,7 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); kept = kept.saturating_add(facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return None; } listed(&surfaces, &facets, &mut out); @@ -3309,7 +3326,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) Err(e) => return Err(e), }; kept = kept.saturating_add(solid.facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()); } match solid.mesh() { diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 49c301dd75..504fe1d777 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1642,17 +1642,36 @@ fn polygon_node(id: u64, corners: usize) -> Node { Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) } +/// Sets the faces the solids of one object keep together ([`OBJECT_FACE_LIMIT`]) to a lower limit +/// on this thread, and sets [`MAX_OBJECT_FACES`] again when dropped, so that a test of the limit +/// builds small solids. +struct FaceLimit(usize); + +impl FaceLimit { + fn set(limit: usize) -> Self { + Self(OBJECT_FACE_LIMIT.with(|l| l.replace(limit))) + } +} + +impl Drop for FaceLimit { + fn drop(&mut self) { + OBJECT_FACE_LIMIT.with(|l| l.set(self.0)); + } +} + /// A group whose members' solids each fit, but not all of them together, draws its source art, and /// the commands that check the effect report the error, as do its mesh and its wireframe; one -/// member fewer, within the limit, draws. +/// member fewer, exactly at the limit, draws. The limit is lowered to three members' faces. #[test] fn a_groups_solids_together_past_the_limit_draw_the_source() { - let member = polygon_node(1, 16_384); + let member = polygon_node(1, 64); let mut alone = member.clone(); alone.appearance.effects.push(fx(EXTRUDE, json!({}))); let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + let limit = 3 * each; + let _limit = FaceLimit::set(limit); // Members stacked in one place each build the same solid. - let fits = MAX_OBJECT_FACES / each; + let fits = limit / each; let group = |count: usize| { let members = (0..count) .map(|k| { @@ -1703,16 +1722,19 @@ fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() { } /// A fill and strokes whose solids each fit, but not all of them together, draw the source art, -/// and the strokes after the one past the limit are not left out to make room. +/// and the strokes after the one past the limit are not left out to make room. The limit is +/// lowered to the fill's faces and three strokes'. #[test] fn a_fill_and_strokes_together_past_the_limit_draw_the_source() { - let mut n = polygon_node(1, 16_384); + let mut n = polygon_node(1, 64); n.appearance.effects.push(fx(EXTRUDE, json!({}))); let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)); n.appearance.items.push(stroke.clone()); // Strokes alike each build the same solid. let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") }; - let fits = (MAX_OBJECT_FACES - fill) / each; + let limit = fill + 3 * each; + let _limit = FaceLimit::set(limit); + let fits = (limit - fill) / each; assert!(fits >= 2, "{fill} + {fits} × {each}"); n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1)); assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}"); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 65ac8b0f7e..409a5c1dc3 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -12,8 +12,8 @@ use vectorcraft_three_d::Facet; use super::{ CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, - is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, - union_bounds, + is_three_d, label_of, members, object_face_limit, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, + solid_parts, union_bounds, }; use crate::{GeomContext, is_geometry}; @@ -258,7 +258,7 @@ pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result>(); let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0)); - let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical); - assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); + let out = anchors(&run("warp.arc", json!({"bend": 50, "version": 1}), &vertical)); + assert!(out.len() >= 2, "{out:?}"); + assert!(out.iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0)); for style in ["bulge", "fisheye", "inflate", "squeeze"] { - let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal); - assert!( - anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), - "{style}: {out:?}" - ); + let out = anchors(&run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal)); + assert!(out.len() >= 2, "{style}: {out:?}"); + assert!(out.iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), "{style}: {out:?}"); } } @@ -1343,10 +1342,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() { fn pucker_bloat_moves_anchors_in_opposite_directions() { let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square()); let a = bloat.subpaths[0].anchors[0].p; - assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}"); + // Half the amount of the way to the centre (50, 50): 25% of 50 pt. + assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}"); let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square()); let a = pucker.subpaths[0].anchors[0].p; - assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}"); + assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}"); assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square()); } @@ -2083,18 +2083,6 @@ fn bad_params_fall_back_to_defaults() { assert!(close(out.bounds().unwrap().width(), 124.0, 0.1)); } -#[test] -#[ignore] -fn bench_catalog_lookup() { - let t = std::time::Instant::now(); - let mut n = 0; - for _ in 0..10_000 { - n += crate::is_geometry("distort.roughen") as usize; - n += crate::merged_params("stylize.dropShadow", &serde_json::Value::Null).as_object().unwrap().len(); - } - eprintln!("10k lookups: {:?} ({n})", t.elapsed()); -} - #[test] fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { use std::sync::Arc; diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index db34010c22..d0e4939e8e 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { use vectorcraft_doc::text::{CharStyle, TextObject}; let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); - if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } + assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths"); let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); let b = baked(g); assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); @@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec) -> Node { n } +/// Whether the face of the default character style is installed, so that type lays out glyphs. +/// When it is, `type_node`'s type must outline to paths. +fn fonts() -> bool { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { + return false; + } + assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family); + true +} + /// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square /// centered on its origin. fn instance(id: u64, effects: Vec) -> (Node, Node) { @@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec) -> (Node, Node) { /// image and the instance are checked. #[test] fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { - let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + let fonts = fonts(); if !fonts { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); } @@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef /// listed before that effect, as the canvas draws it, rather than staying type under one shadow. #[test] fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { - if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } @@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() { n }; let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; - if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 027ae10251..945e6c92be 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -72,10 +72,11 @@ serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } -# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in -# Cargo.lock (tempfile, ui-egui), so this adds no new crate. +# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a +# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, +# ui-egui), so this adds no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "process"] } +rustix = { workspace = true, features = ["std", "process", "fs"] } # Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), # and whether two paths a script names are one file (`script::files`). Already in Cargo.lock @@ -116,7 +117,7 @@ zune-core = { workspace = true } # JPEG XL files for the import fuzz tests (tests/import_fuzz.rs). craft-jxl = { workspace = true } # vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference -# tests/group3_reference.rs compares it with. +# tests/it/group3_reference.rs compares it with. hayro-ccitt = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } @@ -143,3 +144,14 @@ ruzstd = { workspace = true } vectorcraft-js = { workspace = true } # A bundled font's own glyph boxes, for the glyph bounds tests. skrifa = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "crates/affinity/tests/support/corpus.rs", + "crates/affinity/tests/support/text_fixture.rs", + "crates/apischema/src/conformance.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", + "xtask/affinity-corpus.sha256", + "xtask/src/sha256.rs", +] diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 43d6e3a7d4..d2dc185222 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -111,6 +111,7 @@ mod textedit; pub use textedit::effective_kerning; mod retype; +mod stepandrepeat; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(layerpanel::specs()); v.extend(draw2::specs()); v.extend(xform::specs()); + v.extend(stepandrepeat::specs()); v.extend(effectcmd::specs()); v.extend(bevels::specs()); v.extend(wireframe::specs()); @@ -677,8 +679,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`), +/// and for a color with a component too large to store ([`color_is_finite`]). pub fn color_value(v: &Value) -> Option { + given_color(v).filter(color_is_finite) +} + +/// Is every component of `c` finite? A number past `f32::MAX`, such as `{"c": 1e300}`, is stored +/// as an infinity. +pub fn color_is_finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|x| x.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|x| x.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + +/// The color `v` gives, as [`color_value`] reads it, with its components unchecked. +fn given_color(v: &Value) -> Option { match v { Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). @@ -874,6 +892,9 @@ pub(crate) use vectorcraft_doc::range::parse_range; /// What the fill and stroke proxies read from the selected objects, kept with the selection /// ([`crate::doc_state::SelectionRecord`]). pub(crate) use paint::SelectionPaints; +/// The faces and edges of Live Paint groups among objects that count with their group +/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer). +pub(crate) use paint::live_paint_covered; #[cfg(test)] pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ}; @@ -981,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). -pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; +pub const ALIASES: &[(&str, &str)] = + &[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")]; /// Is `id` an [`ALIASES`] entry? pub fn is_alias(id: &str) -> bool { diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index c1e99bb155..25f950ef9a 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -5,11 +5,14 @@ //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected //! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the -//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their +//! visual bounds share, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection -//! (a view command) are the UI's. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view +//! command) are the UI's. +pub mod marks; #[cfg(test)] mod tests; @@ -18,7 +21,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -108,6 +111,15 @@ pub fn specs() -> Vec { has_multi, group_overlapping ), + cmd!( + "addon.arrange.groupRows", + "Group by Row", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_rows + ), cmd!( "addon.arrange.randomizeOpacity", "Randomize Opacity", @@ -127,6 +139,9 @@ pub fn specs() -> Vec { sort ), ] + .into_iter() + .chain(marks::specs()) + .collect() } /// Exactly two objects are selected (Swap Objects). @@ -577,11 +592,110 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result { roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); let keyed: Vec<(Option, Rect)> = items.iter().map(|(_, k)| *k).collect(); let sets: Vec> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + group_each(s, "Group Overlapping Objects", &roots, sets) +} + +/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of +/// two or more (each in the order given) among items of the same key whose extents overlap, chains included. +/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it +/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at +/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which +/// `total_cmp` would otherwise order first. +fn rows_of(items: &[(K, (f64, f64))]) -> Vec> { + let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect(); + let mut order: Vec = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1))); + let mut rows: Vec> = vec![]; + // Each key's open row: its index in `rows` and where it ends. + let mut open: HashMap = HashMap::new(); + for i in order { + let (key, (start, end)) = items[i]; + match open.get_mut(&key) { + Some((row, until)) if start < *until => { + if let Some(r) = rows.get_mut(*row) { + r.push(i); + } + *until = until.max(end); + } + _ => { + open.insert(key, (rows.len(), end)); + rows.push(vec![i]); + } + } + } + rows.retain(|r| r.len() > 1); + for r in &mut rows { + r.sort_unstable(); + } + rows +} + +fn group_rows(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.groupRows"; + if !p.is_object() { + return Err(bad(C, "parameters must be an object")); + } + if p.get("direction").is_some_and(Value::is_null) { + return Err(bad(C, "`direction` must be row or column")); + } + let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let editable_roots: Vec<_> = { + let editable = d.editable(); + roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect() + }; + for id in &editable_roots { + let parent = d.parent_of(*id); + let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| { + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && n.extras().shaper.is_none() + && n.extras().objects_on_path.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) + }); + let in_graph = parent + .and_then(|parent| d.ancestry(parent)) + .is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some()))); + if !valid_parent || in_graph { + return Err(bad(C, "selected objects must be in a layer or group without live structural roles")); + } + } + // Each object's row key (its parent and its artboard) and its extent across the rows. + type Keyed = ((NodeId, usize), (f64, f64)); + let symbols = d.symbol_boxes(); + let items: Vec<(NodeId, Keyed)> = editable_roots + .iter() + .filter_map(|id| { + let parent = d.parent_of(*id)?; + let container = d.node(parent)?; + if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) { + return None; + } + let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?; + let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; + Some((*id, ((parent, d.artboard_for_bounds(b)?), extent))) + }) + .collect(); + let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + let mut selection = roots; + selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer()))); + group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets) +} + +/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a +/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and +/// the objects of `roots` left alone. No step when `sets` is empty. +fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec>) -> Result { if sets.is_empty() { return Ok(json!({ "groups": [], "grouped": 0 })); } let grouped: std::collections::HashSet = sets.iter().flatten().copied().collect(); - let groups = s.edit("Group Overlapping Objects", |d, sel| { + let groups = s.edit(label, |d, sel| { // Every group at once: the members behind each front one go, then each front one is // replaced by its group (one pass over the tree each, however many groups). let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs new file mode 100644 index 0000000000..fc01a8730d --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -0,0 +1,147 @@ +//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds +//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than +//! around the whole selection, stroked in a color of their own and stacked directly above the +//! object, as one undo step. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_render::drawn_bounds_with; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::paint::new_color; +use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection}; +use super::{LEAST, LIMIT, MAX_OBJECTS, number_in}; +use crate::{Result, Session}; + +/// The command. +pub const COMMAND: &str = "addon.arrange.markBounds"; +/// The heaviest stroke (pt) the marks take, and the lightest. +const MAX_WEIGHT: f64 = 1000.0; +const MIN_WEIGHT: f64 = 0.01; +/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one. +const FLAT: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.arrange.markBounds", + "Mark Bounds of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + has_selection, + mark_bounds + )] +} + +/// The four corners of `r`, each with the directions its legs run in (inward), the corners that +/// fall on an earlier one left out. +fn corners(r: Rect) -> Vec<(Point, f64, f64)> { + let mut out: Vec<(Point, f64, f64)> = vec![]; + for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] { + let at = Point::new(x, y); + if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) { + out.push((at, sx, sy)); + } + } + out +} + +/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per +/// corner, a line where `r` has no width or no height. +fn corner_paths(r: Rect, length: f64) -> Vec { + let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + corners(r) + .into_iter() + .filter_map(|(p, sx, sy)| { + let across = Point::new(p.x + sx * lx, p.y); + let down = Point::new(p.x, p.y + sy * ly); + let points = match (lx > FLAT, ly > FLAT) { + (true, true) => vec![across, p, down], + (true, false) => vec![across, p], + (false, true) => vec![p, down], + (false, false) => return None, + }; + Some(PathData::single(SubPath::polyline(&points, false))) + }) + .collect() +} + +/// Where the marks of object `id` go: directly above it, or above the outermost clip group or +/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. +fn anchor(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut outermost) = (id, id); + while let Some(up) = d.parent_of(at) { + if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + outermost = up; + } + at = up; + } + outermost +} + +fn mark_bounds(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); + let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual"); + let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?; + let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?; + let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0))); + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + for id in roots { + let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; + if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { + marked.push((anchor(d, id), r)); + } + } + if marked.is_empty() { + return Err(bad(C, "nothing to mark: the selection has no bounds")); + } + let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); + let ids = s.edit("Mark Bounds of Each", |d, sel| { + // Each anchor once, its objects' marks in stacking order from the back. + let mut lists: Vec<(NodeId, Vec)> = vec![]; + let mut at: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(marked.len()); + for (anchor, r) in &marked { + let node = if rectangle { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone()); + n.name = Some("Bounds".into()); + n + } else { + let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect(); + let mut g = Node::group(d.alloc_id(), children); + g.name = Some("Corner Marks".into()); + g + }; + out.push(node.id); + let k = *at.entry(*anchor).or_insert_with(|| { + lists.push((*anchor, vec![])); + lists.len() - 1 + }); + if let Some((_, nodes)) = lists.get_mut(k) { + nodes.push(node); + } + } + d.insert_beside(lists, false)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "count": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs new file mode 100644 index 0000000000..dc44f47d5b --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -0,0 +1,353 @@ +//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how +//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_geom::Rect; + +use super::COMMAND; +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +/// The ids of the children of `parent`, in stacking order from the back. +fn children(s: &Session, parent: NodeId) -> Vec { + node(s, parent).children().unwrap().iter().map(|n| n.id).collect() +} + +fn parent(s: &Session, id: NodeId) -> NodeId { + s.doc().unwrap().doc.parent_of(id).unwrap() +} + +/// Each path of the mark `id` (a group's members, or the path itself) as its points. +fn lines(s: &Session, id: NodeId) -> Vec> { + let n = node(s, id); + let paths: Vec = match n.children() { + Some(c) => c.iter().map(|c| (**c).clone()).collect(), + None => vec![n], + }; + paths + .iter() + .map(|p| { + let path = p.path_data().unwrap(); + path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect() + }) + .collect() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn marks_bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +#[test] +fn each_object_gets_inward_corner_marks_above_it_in_one_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0); + let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0); + let layer = parent(&s, a); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let marks = ids_of(&r); + assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2))); + // Directly above each object, not around the selection. + assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected"); + assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks")); + assert_eq!( + lines(&s, marks[0]), + vec![ + vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)], + vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)], + vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)], + ] + ); + assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0))); + // A red 1 pt stroke and no fill. + let group = node(&s, marks[1]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![a, b]); +} + +#[test] +fn length_weight_color_and_the_rectangle_style() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap(); + let marks = ids_of(&r); + // A leg is never longer than half its side, so opposite marks do not overlap. + assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]); + let group = node(&s, marks[0]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5)); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + let rect = node(&s, mark); + assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path"); + assert_eq!(rect.name.as_deref(), Some("Bounds")); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0))); +} + +#[test] +fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 30})).unwrap(); + assert_eq!( + lines(&s, ids_of(&r)[0]), + vec![ + vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)], + vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)], + vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)], + ] + ); +} + +#[test] +fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); +} + +#[test] +fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() { + let mut s = session(); + let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0); + select(&mut s, &[a]); + let geometry = marks_bounds(&s, a); + let (dx, dy) = (12.0, 8.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap(); + let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy); + let reach = geometry.union(shadow); + let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves the shadow outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}"); +} + +#[test] +fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() { + for grouped in [false, true] { + let mut s = session(); + let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[path]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 1})).unwrap(); + s.execute("brush.apply", &json!({"name": "Dots"})).unwrap(); + let target = if grouped { + s.execute("object.group", &json!({})).unwrap(); + parent(&s, path) + } else { + path + }; + select(&mut s, &[target]); + let geometry = marks_bounds(&s, path); + let d = &s.doc().unwrap().doc; + let source = d.node(target).unwrap(); + let painted = vectorcraft_render::painted_bounds(d, source).unwrap(); + let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap(); + let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap(); + assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}"); + let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves brush art outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}"); + assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}"); + assert!( + visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1, + "the visual mark stays inside the culling margin: {visual:?}, {painted:?}" + ); + } +} + +#[test] +fn groups_by_their_members_and_clip_groups_by_the_clipping_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let group = parent(&s, a); + let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0); + let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0); + select(&mut s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = parent(&s, art); + let layer = parent(&s, group); + select(&mut s, &[group, clip_group]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let marks = ids_of(&r); + assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together"); + assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path"); + assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + // An object inside the clip group: its marks go above the clip group, where it does not hide them. + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, layer), vec![group, clip_group, mark]); + assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + // And when a plain group lies between the object and the clip group. + select(&mut s, &[art]); + s.execute("object.group", &json!({})).unwrap(); + let inner = parent(&s, art); + let clip_group = parent(&s, clip); + assert_eq!(parent(&s, inner), clip_group); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]); +} + +#[test] +fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer"); + + // A clipping top-level layer has nothing outside it to hold them: they go above the object. + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + let stack = children(&s, top); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); +} + +#[test] +fn flat_objects_get_lines_and_guides_and_empty_groups_none() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[line]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + // No height: one mark at each end, along the line. + assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]); + s.execute("edit.undo", &json!({})).unwrap(); + + let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + select(&mut s, &[guide]); + let layer = s.doc().unwrap().target_parent().unwrap(); + let empty = s + .edit("test", |d, _| { + let g = Node::group(d.alloc_id(), vec![]); + let id = g.id; + d.insert(layer, usize::MAX, g)?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[guide, empty]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // With a real object as well, only it gets marks. + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[guide, empty, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + +#[test] +fn bad_params_are_refused_and_it_is_off_without_a_selection() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"style": "cross"}), + json!({"bounds": "preview"}), + json!({"length": 0}), + json!({"length": 1e7}), + json!({"length": "10"}), + json!({"weight": 0}), + json!({"weight": 1001}), + json!({"color": "not a color"}), + json!({"color": "#ff000080"}), + json!({"color": 3}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 265ab50a6a..a3c44bd9db 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -779,6 +779,7 @@ fn off_without_a_selection() { "addon.arrange.size", "addon.arrange.match", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", "addon.arrange.randomizeOpacity", "addon.arrange.sort", ] { @@ -862,6 +863,503 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() { assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); } +fn layer_children(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_rows_groups_each_row_and_leaves_loners() { + let mut s = session(); + // Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0); + let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0); + let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0); + select(&mut s, &[a, b, c, d, e]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(4)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order"); + assert_eq!(children(&s, groups[1]), [d, e]); + // Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e. + assert_eq!(layer_children(&s), [groups[0], c, groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_children(&s), [a, d, b, c, e]); +} + +#[test] +fn group_rows_makes_columns_and_joins_rows_an_object_spans() { + let mut s = session(); + // Columns: a and b share x 0 to 15, c stands apart. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0); + let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, b, c]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, b]); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column")); + // By row, p and q lie in two rows until r, reaching from one to the other, joins them. + let mut s = session(); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0); + select(&mut s, &[p, q]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step"); + let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0); + select(&mut s, &[p, q, bridge]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [p, q, bridge]); +} + +#[test] +fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // Touching a's bottom edge: a row of its own until strokes reach over the edge. + let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0); + let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, below, far, other]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups"); + select(&mut s, &[a, below]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, below, far, other]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap"); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard"); + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_rows_measures_clipping_groups_by_their_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // A 200 tall object clipped to a 30 tall mask at y 100. + let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0); + let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0); + select(&mut s, &[clipped, mask]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0]; + let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0); + select(&mut s, &[a, group, b]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's"); +} + +#[test] +fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() { + for clipping_layer in [false, true] { + let mut s = session(); + let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + select(&mut s, &[mask, a, b]); + let parent = if clipping_layer { + s.doc().unwrap().doc.layers[0].id + } else { + s.execute("object.group", &json!({})).unwrap(); + s.doc().unwrap().selection.objects[0] + }; + s.edit("Set clipping", |d, _| { + d.node_mut(parent).unwrap().set_clips(true); + Ok(()) + }) + .unwrap(); + select(&mut s, &[mask, a]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(children(&s, parent), [mask, a, b]); + select(&mut s, &[mask, a, b]); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, parent), [mask, groups[0]]); + assert_eq!(children(&s, groups[0]), [a, b]); + assert!(s.doc().unwrap().selection.objects.contains(&mask)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_leaves_selected_layers_and_sublayers_in_place() { + for sublayers in [false, true] { + let mut s = session(); + let parent = s.doc().unwrap().doc.layers[0].id; + let mut layers = vec![]; + for _ in 0..2 { + let command = if sublayers { "layer.newSublayer" } else { "layer.new" }; + let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) }; + let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap()); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + layers.push(layer); + } + s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &layers); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + select(&mut s, &[layers[0], layers[1], a, b]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(2)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(&s, groups[0]), [a, b]); + for layer in &layers { + assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent)); + assert!(s.doc().unwrap().selection.objects.contains(layer)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + +#[test] +fn group_rows_refuses_objects_without_a_parent() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + s.edit("Set root objects", |d, _| { + for id in [a, b] { + let node = d.remove(id)?; + d.layers.push(node); + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]); +} + +fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec]) { + let center = bounds(s, group).center(); + let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0); + let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0); + let members = children(s, group); + for direction in ["row", "column"] { + for selected in parts { + select(s, selected); + let selection = s.doc().unwrap().selection.clone(); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(s.doc().unwrap().selection, selection); + let mut mixed = selected.clone(); + mixed.extend([a, b]); + select(s, &mixed); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(s, group), members); + } + select(s, &[group, a, b]); + let before = s.doc().unwrap().doc.clone(); + let n = steps(s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(3)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(s, groups[0]), [group, a, b]); + assert_eq!(children(s, group), members); + assert_eq!(steps(s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() { + let mut s = session(); + let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0); + let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap()); + refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]); + assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some()); +} + +#[test] +fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(group).unwrap(); + let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect(); + let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect(); + assert!(faces.len() >= 2); + assert!(edges.len() >= 2); + refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]); + let node = s.doc().unwrap().doc.node(group).unwrap(); + assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::>(), faces); + assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::>(), edges); +} + +#[test] +fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() { + let mut s = session(); + let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"}); + let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(graph).unwrap(); + let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect(); + assert_eq!(marks.len(), 2); + let direct = children(&s, graph); + refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]); + assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some()); +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_blend_keys() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + assert_eq!(children(&s, blend), [a, b]); +} + +#[test] +fn group_rows_refuses_explicitly_selected_shaper_children() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap()); + let members = children(&s, shaper); + assert!(members.len() >= 2); + let sources = members[0]; + let face = s + .doc() + .unwrap() + .doc + .node(shaper) + .unwrap() + .children() + .unwrap() + .iter() + .find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX))) + .unwrap() + .id; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[sources, face]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[sources, face, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shaper), members); + } +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0); + select(&mut s, &[a, b]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shape), [a, b]); + } +} + +#[test] +fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() { + for command in ["object.lock", "object.hide"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[b]); + s.execute(command, &json!({})).unwrap(); + select(&mut s, &[a, b, c]); + assert!(s.doc().unwrap().selection.objects.contains(&b)); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [a, c]); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); + } +} + +#[test] +fn group_rows_leaves_objects_outside_all_artboards_ungrouped() { + for direction in ["row", "column"] { + let mut s = session(); + let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0); + let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert!(*s.doc().unwrap().doc == *before); + let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0); + select(&mut s, &[a, b, c, d]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [c, d]); + assert_eq!(layer_children(&s), [a, b, groups[0]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + } +} + +#[test] +fn group_rows_documents_and_excludes_raster_effects_from_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap(); + let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), [a, b]); + let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap(); + assert!(spec.params.contains("excludes raster effects")); +} + +#[test] +fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupRows")); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b, c]); + assert!(enabled(&s, "addon.arrange.groupRows")); + refuses( + &mut s, + "addon.arrange.groupRows", + &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})], + ); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out"); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); +} + +#[test] +fn group_rows_refuses_non_object_params_without_an_edit() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let selection = s.doc().unwrap().selection.objects.clone(); + refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]); + assert_eq!(s.doc().unwrap().selection.objects, selection); +} + +#[test] +fn group_rows_reads_the_symbol_index_once_for_all_members() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + + let mut d = Document::new(400.0, 300.0); + for i in 0..200 { + let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) }); + } + let layer = d.layers[0].id; + let ids: Vec<_> = (0..8) + .map(|i| { + let xf = Affine::translate((0.0, f64::from(i) * 20.0)); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let symbol_count = d.symbols.len(); + let mut s = Session::new(); + s.add_document(d, None); + select(&mut s, &ids); + let n = steps(&s); + let before = vectorcraft_doc::symbols_read(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document"); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), ids); +} + +#[test] +fn group_rows_sorts_many_objects_into_rows() { + // 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps, + // neighboring pairs only touch. + let items: Vec<(u8, (f64, f64))> = (0..20_000) + .map(|i| { + let top = (10_000 - i / 2) as f64 * 10.0; + (0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0)) + }) + .collect(); + let rows = super::rows_of(&items); + assert_eq!(rows.len(), 10_000); + assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given"); + assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first"); +} + +#[test] +fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() { + // An extent with no height at the top edge of another only touches it, whichever is in front. + let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))]; + let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))]; + assert!(super::rows_of(&flat_behind).is_empty()); + assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front)); + // Inside the row, it joins. + assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]); + // A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches. + let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))]; + assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero)); +} + fn opacity(s: &Session, id: NodeId) -> f32 { s.doc().unwrap().doc.node(id).unwrap().opacity } diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index c12eb2fa64..a9f1b48166 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -5,12 +5,14 @@ //! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest //! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend //! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply -//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, +//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors +//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu, //! Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; mod print_fixes; +mod random_fill; #[cfg(test)] mod tests; @@ -92,6 +94,15 @@ pub fn specs() -> Vec { has_doc, |s, p| copy_paint(s, p, false) ), + cmd!( + "addon.color.randomFill", + "Randomize Fill Colors", + ["Object", "Plug-ins", "Color Effects"], + None, + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + has_selection, + random_fill::run + ), ] .into_iter() .chain(legend::specs()) diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs new file mode 100644 index 0000000000..eaf78e5660 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -0,0 +1,255 @@ +//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize +//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected +//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one +//! global or spot swatch, or a gray, as one undo step. + +#[cfg(test)] +mod tests; + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; + +use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; +#[cfg(test)] +use super::super::super::graph::is_design_art; +use super::super::super::graph::{is_series_group, paint_targets}; +use super::super::super::menucmds::whole_or; +use super::super::super::paint::swatch_solid; +use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; +use crate::{Result, Session}; + +const C: &str = "addon.color.randomFill"; +/// The schemes the colors are picked from (`scheme`). +pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"]; + +/// How each color is picked. +enum Scheme { + /// Any color: red, green and blue each at random, in the document's color mode. + Color, + /// A tint of the swatch, from the least to the most (0..1). + Tint(String, f32, f32), + /// A gray, from the least black to the most (0..1). + Gray(f32, f32), +} + +/// The percentage `p` gives for `key` (`default` when left out). +fn percent(p: &Value, key: &str, default: f64) -> Result { + let v = number_or(p, key, default, C)?; + if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } +} + +/// The scheme `p` asks for, checked against the document's swatches. +fn scheme(s: &Session, p: &Value) -> Result { + let name = text_param(p, "scheme", C)?.unwrap_or("color"); + if !SCHEMES.contains(&name) { + return Err(bad(C, "`scheme` must be color, tint or gray")); + } + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + if name == "color" && (given("min") || given("max")) { + return Err(bad(C, "`min` and `max` go with scheme tint or gray")); + } + if name != "tint" && given("swatch") { + return Err(bad(C, "`swatch` goes with scheme tint")); + } + if name == "color" { + return Ok(Scheme::Color); + } + let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?); + if min > max { + return Err(bad(C, "`min` is greater than `max`")); + } + let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32); + if name == "gray" { + return Ok(Scheme::Gray(min, max)); + } + let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?; + let d = &s.doc()?.doc; + swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?; + if let Some((base, _)) = d.swatch_link(swatch) + && d.tint_paint(&base, 1.0).is_none() + { + return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`"))); + } + Ok(Scheme::Tint(swatch.to_string(), min, max)) +} + +/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or +/// locked, or it is the clipping path of the group or layer holding it. +fn left_alone(d: &Document, id: NodeId) -> bool { + let Some(line) = d.ancestry(id) else { return true }; + let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect(); + if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) { + return true; + } + matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) +} + +/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the +/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping +/// group or clipped layer, a compound path included), a guide, type, images, symbol instances, +/// blends and envelopes are left as they are. +fn filled(n: &Node, out: &mut Vec) { + if !n.visible || n.locked { + return; + } + if n.is_compound_shape() { + if !n.appearance.fill_paint().is_none() { + out.push(n.id); + } + return; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter().skip(usize::from(n.clips())) { + filled(c, out); + } + } + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id), + _ => {} + } +} + +/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside +/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through +/// [`paint_targets`], as for `paint.setFill`. +fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec { + let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n)); + let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape(); + let ordinary: std::collections::HashSet = paint_targets(doc, ids).into_iter().collect(); + let mut out = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + if is_series(*id) { + out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id)); + } else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) { + out.push(*id); + } + } + let mut seen = std::collections::HashSet::new(); + out.retain(|id| seen.insert(*id)); + out +} + +/// The graph series groups among the ancestors of `targets`, each checked once. +fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet { + let mut groups: HashSet = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect(); + groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n))); + groups +} + +/// [`is_design_art`] with the series groups looked up in `series_groups`. +fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet) -> bool { + let Some(chain) = doc.ancestry(id) else { return false }; + let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false }; + match chain.len() - at { + 1 => false, + 2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })), + _ => true, + } +} + +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let scheme = scheme(s, p)?; + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let ids = checked_ids_or_selection(s, p, C)?; + if ids.is_empty() { + return Ok(json!({ "count": 0 })); + } + let model = s.doc()?.doc.color_mode.model(); + // A run that gives every object the fill it has records no undo step. + let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| { + // Art on a locked artboard is left as it is, as for the other commands that take `ids`. + let locks = before.locked_artboards(); + // A nested member stands for the outermost compound path or live compound shape after each ancestor is checked. + let mut resolved = vec![]; + for id in &ids { + let Some(chain) = before.ancestry(*id) else { continue }; + let mut target = None; + let mut blocked = false; + let mut parent: Option<&Node> = None; + let mut layer_object_checked = false; + for ancestor in &chain { + let Some(n) = before.node(*ancestor) else { + blocked = true; + break; + }; + if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) { + blocked = true; + break; + } + if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) { + layer_object_checked = true; + if !n.is_ruler_guide() && locks.holds(n) { + blocked = true; + break; + } + } + if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() { + target.get_or_insert(*ancestor); + } + parent = Some(n); + } + if !blocked { + resolved.push(target.unwrap_or(*id)); + } + } + // A graph's series group stands for its marks, as for `paint.setFill`. + let roots = series_roots(before, &resolved); + let mut targets = vec![]; + for id in &roots { + let id = *id; + if left_alone(before, id) || locks.holds_id(id) { + continue; + } + let Some(n) = before.node(id) else { continue }; + filled(n, &mut targets); + } + let series_groups = cached_series_groups(before, &targets); + let mut seen = std::collections::HashSet::new(); + // A compound directly in a series group is one of the series' marks unless the graph drew it from a design; + // the rest of the series' art below its top level is design art. + let series_compound = |id: NodeId| { + let Some(n) = before.node(id) else { return false }; + if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { + return false; + } + let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false }; + let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; + let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref()); + graph.is_some_and(|spec| { + let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str()); + let marker = spec.series_markers.get(index).and_then(Option::as_deref); + ![column, marker].into_iter().flatten().any(|name| { + before + .graph_designs + .iter() + .any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())) + }) + }) + }; + targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups))); + let count = keeping_series_paint(d, &roots, |d| { + let mut count = 0; + for id in &targets { + let paint = match &scheme { + Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)), + Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?, + Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))), + }; + if let Some(n) = d.node_mut(*id) + && n.appearance.fill_paint() != paint + { + n.appearance.set_fill(paint); + count += 1; + } + } + Ok(count) + })?; + Ok((count, count > 0)) + })?; + Ok(json!({ "count": count })) +} diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs new file mode 100644 index 0000000000..11b4f989be --- /dev/null +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -0,0 +1,705 @@ +//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and +//! bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +const C: &str = "addon.color.randomFill"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap()) +} + +fn rects(s: &mut Session, n: usize) -> Vec { + (0..n).map(|i| rect(s, i as f64 * 10.0)).collect() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn fill(s: &Session, id: NodeId) -> Paint { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() +} + +fn fills(s: &Session, ids: &[NodeId]) -> Vec { + ids.iter().map(|id| fill(s, *id)).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn enabled(s: &Session, cmd: &str) -> bool { + s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled +} + +#[test] +fn each_object_gets_its_own_color_from_the_seed() { + let mut s = session(); + let ids = rects(&mut s, 12); + select(&mut s, &ids); + let before = fills(&s, &ids); + let n = steps(&s); + let r = s.execute(C, &json!({"seed": 7})).unwrap(); + assert_eq!(r["count"], json!(12)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let first = fills(&s, &ids); + assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}"); + assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fills(&s, &ids), before, "undone"); + // The same seed repeats them; another seed doesn't. + s.execute(C, &json!({"seed": 7})).unwrap(); + assert_eq!(fills(&s, &ids), first); + s.execute(C, &json!({"seed": 8})).unwrap(); + assert_ne!(fills(&s, &ids), first); +} + +#[test] +fn repeated_ids_take_one_color_from_the_seed() { + let mut s = session(); + let a = rect(&mut s, 0.0); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1)); + let once = fill(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1)); + assert_eq!(fill(&s, a), once); +} + +#[test] +fn a_cmyk_document_gets_cmyk_colors() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let ids = rects(&mut s, 3); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "color"})).unwrap(); + assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids)); +} + +#[test] +fn grays_and_tints_stay_within_the_range() { + let mut s = session(); + let ids = rects(&mut s, 20); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap(); + let grays: Vec = fills(&s, &ids) + .into_iter() + .map(|p| match p { + Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k, + other => panic!("not a gray: {other:?}"), + }) + .collect(); + assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}"); + assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap(); + for p in fills(&s, &ids) { + let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") }; + assert_eq!(name, "Ink"); + assert!((0.1..=0.5).contains(&tint), "{tint}"); + } + // min = max gives every object that gray. + s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap(); + assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45)))); +} + +#[test] +fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() { + let mut s = session(); + let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b, c, hidden, locked]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap(); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + select(&mut s, &[g]); + let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked)); + assert!(!before_hidden.is_none() && !before_locked.is_none()); + let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap(); + assert_eq!(r["count"], json!(2)); + let gray = Paint::solid(Color::gray(0.5)); + assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None"); + assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own"); + assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked)); + // `ids` stand in for the selection; with nothing selected the menu item is off. + s.execute("select.none", &json!({})).unwrap(); + assert!(!enabled(&s, C)); + let d = rect(&mut s, 50.0); + s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap(); + assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1))); + assert_eq!(fill(&s, a), gray, "not among ids"); + // An object given by id inside a hidden or locked group keeps its fill. + for hide in [true, false] { + let e = rect(&mut s, 60.0); + s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap(); + select(&mut s, &[e]); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap(); + let kept = fill(&s, e); + assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}"); + assert_eq!(fill(&s, e), kept); + } +} + +#[test] +fn a_compound_path_takes_one_color_and_a_clipping_path_none() { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + // The topmost becomes the clipping path. + let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x)); + select(&mut s, &[art, mask]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. }); + assert!(is_clipping(&s, mask) && !is_clipping(&s, art)); + // A clipping path given a fill still keeps it. + s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap(); + let mask_fill = fill(&s, mask); + assert!(!mask_fill.is_none()); + select(&mut s, &[compound, clip]); + let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(r["count"], json!(2), "the compound path and the clipped art"); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill"); + // Given by id, the clipping path keeps it too. + assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0)); + assert_eq!(fill(&s, mask), mask_fill); +} + +#[test] +fn a_compound_member_given_by_id_colors_the_compound() { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let before = fill(&s, compound); + let members = fills(&s, &[a, b]); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1)); + assert_ne!(fill(&s, compound), before); + assert_eq!(fills(&s, &[a, b]), members); +} + +#[test] +fn a_compound_clipping_path_keeps_its_fill() { + let mut s = session(); + let art = rect(&mut s, 0.0); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[art, compound]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips"); + s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap(); + let mask_fill = fill(&s, compound); + assert!(!mask_fill.is_none()); + select(&mut s, &[clip]); + assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only"); + assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, compound), mask_fill); +} + +#[test] +fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() { + for target in ["shape", "group", "member"] { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape()); + let id = match target { + "group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()), + "member" => a, + _ => shape, + }; + let before = fill(&s, shape); + let members = fills(&s, &[a, b]); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}"); + assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}"); + assert_eq!(fills(&s, &[a, b]), members, "{target}"); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s, shape), before); + assert_eq!(fills(&s, &[a, b]), members); + } +} + +#[test] +fn a_selected_graph_keeps_the_fills_of_generated_design_art() { + let mut s = session(); + let a = rect(&mut s, 0.0); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap(); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let mut design_paths = vec![]; + let d = &s.doc().unwrap().doc; + d.node(graph).unwrap().walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() { + design_paths.push(n.id); + } + }); + assert!(!design_paths.is_empty()); + let before = fills(&s, &design_paths); + select(&mut s, &[graph]); + s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(fills(&s, &design_paths), before); +} + +#[test] +fn a_compound_path_in_a_graph_series_takes_a_color() { + let mut s = session(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); + assert!(marks.len() >= 2); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group"); + for ids in [vec![compound], vec![marks[0]], vec![group]] { + let before = fill(&s, compound); + let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}"); + assert_ne!(fill(&s, compound), before, "{ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Tile"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.is_empty()); + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let index = series.extras().series_index.unwrap() as usize; + let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap(); + if kind == "column" { + assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile"); + } else { + assert_eq!(spec.series_markers[index].as_deref(), Some("Tile")); + } + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}"); + let before = fill(&s, compound); + let members = fills(&s, marks); + select(&mut s, &[graph]); + let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert!(result["count"].as_u64().unwrap() >= 1, "{kind}"); + assert_ne!(fill(&s, compound), before, "{kind}"); + assert_eq!(fills(&s, marks), members, "{kind}"); + } +} + +#[test] +fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. })); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + s.edit("Set series design without replacing ordinary marks", |d, _| { + d.node_mut(graph).unwrap().extras_mut().graph = designed; + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}"); + assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}"); + let members = fills(&s, marks); + for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] { + let before = fill(&s, compound); + let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}"); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}"); + assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}"); + assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + } +} + +#[test] +fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}"); + let before = fills(&s, marks); + select(&mut s, &[graph]); + // `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command. + s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap(); + let after_set_fill = fills(&s, marks); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert_eq!(fills(&s, marks), before, "{kind}"); + assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too"); + } +} + +#[test] +fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() { + // `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the + // reference, so each check keeps the copies' fills on its own. + let modes = [(false, false), (true, false), (false, true)]; + for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) { + let mut s = session(); + let marks = rects(&mut s, 2); + select(&mut s, &marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap(); + select(&mut s, &[compound]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let copies: Vec = + series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect(); + assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group"); + for id in &copies { + assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}"); + assert!(super::is_design_art(d, *id), "{kind}"); + } + let mut art = vec![]; + series.walk(&mut |n| { + if super::is_design_art(d, n.id) { + art.push(n.id); + } + }); + if legacy { + s.edit("Clear graph design flags", |d, _| { + for id in &art { + d.node_mut(*id).unwrap().extras_mut().graph_design_art = false; + } + Ok(()) + }) + .unwrap(); + } + if flag_only { + s.edit("Clear series design reference", |d, _| { + let mut extras = d.node_mut(graph).unwrap().extras_mut(); + let spec = extras.graph.as_deref_mut().unwrap(); + spec.series_columns.iter_mut().for_each(|c| *c = None); + spec.series_markers.iter_mut().for_each(|m| *m = None); + Ok(()) + }) + .unwrap(); + for id in &copies { + assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}"); + } + } + let before = fills(&s, &art); + let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] }; + for ids in runs { + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}"); + } + } +} + +#[test] +fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() { + for hide in [true, false] { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap(); + let member = s.doc().unwrap().doc.node(a).unwrap(); + assert!(if hide { !member.visible } else { member.locked }); + let parent = s.doc().unwrap().doc.node(compound).unwrap(); + assert!(parent.visible && !parent.locked); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}"); + assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint()); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); + } +} + +#[test] +fn seeded_colors_follow_ids_order_without_repeating_objects() { + let mut s = session(); + let ids = rects(&mut s, 3); + s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::>(), "seed": 7})).unwrap(); + let first = fills(&s, &ids); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3)); + assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first); +} + +#[test] +fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() { + for blocked in ["none", "hidden", "locked", "artboard"] { + let mut s = session(); + let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[group, b]); + let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[inner, c]); + let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + match blocked { + "hidden" => { + s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap(); + } + "locked" => { + s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap(); + } + "artboard" => { + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + } + _ => {} + } + let before = s.doc().unwrap().doc.clone(); + let members = fills(&s, &[a, b, c, group, inner]); + let n = steps(&s); + let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}"); + if blocked == "none" { + assert_eq!(r["count"], json!(1)); + assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3))); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + } else { + assert_eq!(r["count"], json!(0), "{blocked}"); + assert_eq!(steps(&s), n, "{blocked}"); + } + assert!(*s.doc().unwrap().doc == *before, "{blocked}"); + } +} + +#[test] +fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() { + let mut s = session(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let group = series.id; + let marks: Vec = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect(); + assert!(!marks.is_empty()); + select(&mut s, &marks); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Set series index", |d, _| { + d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX); + Ok(()) + }) + .unwrap(); + let before = fills(&s, &marks); + let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(r["count"], json!(marks.len())); + assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3)))); + assert_ne!(fills(&s, &marks), before); + assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty()); +} + +#[test] +fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() { + let mut s = session(); + let ids = rects(&mut s, 2); + select(&mut s, &ids); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string(); + s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.swatch("Ink").is_none()); + assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4))); + let before = d.clone(); + let n = steps(&s); + let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string(); + assert!(e.contains("base swatch `Ink`"), "{e}"); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); +} + +#[test] +fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("`min` is greater than `max`"), "{p}: {e}"); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); + } +} + +#[test] +fn no_undo_step_when_no_fill_changes() { + let mut s = session(); + let ids = rects(&mut s, 2); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + let n = steps(&s); + let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again"); + // Only unfilled objects: nothing to color. + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0)); + assert_eq!(steps(&s), n); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let bad: [(Value, &str); 14] = [ + (json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"), + (json!({"scheme": 3}), "`scheme` must be a string"), + (json!({"min": 10}), "`min` and `max` go with scheme tint or gray"), + (json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"), + (json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"), + (json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"), + (json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"), + (json!({"scheme": "gray", "max": "50"}), "`max` must be a number"), + (json!({"scheme": "tint"}), "scheme tint needs a `swatch`"), + (json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"), + (json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"), + (json!({"seed": -1}), "`seed` must be a whole number"), + (json!({"seed": 1.5}), "`seed` must be a whole number"), + (json!({"ids": [999_999]}), "no such object id"), + ]; + for (p, want) in bad { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} + +#[test] +fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let before = fill(&s, a); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0)); + assert_eq!(fill(&s, a), before); + assert_eq!(steps(&s), n); +} diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs index 46c33a3871..b1e76927c6 100644 --- a/crates/engine/src/cmd/addons/image/mask/tests.rs +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -449,6 +449,7 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() { }) .unwrap() .to_rgba8(); + assert_eq!(own.dimensions(), (6, 5), "the cut's pixels"); assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included"); assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap(); diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 4d4eb9cdf8..6e02292917 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -3,7 +3,7 @@ //! the bridges connect, replacing the circles or added above them. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; use vectorcraft_pathops::addons::pathtools as pt; @@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec { vec![cmd!( "addon.pathtools.bridge", "Smooth Bridge", - ["Object", "Plug-ins", "Path Precision Tools"], + [], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)", has_selection, bridge )] } -fn bridge(s: &mut Session, p: &Value) -> Result { +pub(super) fn bridge(s: &mut Session, p: &Value) -> Result { let percent = given(p, "radius", Some(RADII), C)?; let gap = given(p, "gap", Some(GAPS), C)?; let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); @@ -54,24 +54,37 @@ fn bridge(s: &mut Session, p: &Value) -> Result { None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0), }; let keep = switch_or(p, "keepOriginals", false, C)?; - let mut roots = checked_ids_or_selection(s, p, C)?; - // An id given twice is one circle. + let mut roots = members(&s.doc()?.doc, &checked_ids_or_selection(s, p, C)?); + // An id given twice, or a circle given with its group, is one circle. roots.sort_unstable(); roots.dedup(); if roots.len() > pt::MAX_BRIDGED_CIRCLES { return Err(bad(C, "select at most 2000 circles to bridge")); } - let circles: Vec<(NodeId, pt::Circle)> = { + // The circles, and why the first object that is not one is refused. + let (circles, why): (Vec<(NodeId, pt::Circle)>, Option<&str>) = { let d = &s.doc()?.doc; let editable = d.editable(); - d.paint_order(roots.iter().copied()) + let mut why = None; + let circles = d + .paint_order(roots.iter().copied()) .into_iter() - .filter_map(|id| match &d.node(id)?.kind { - NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), - _ => None, + .filter_map(|id| { + let found = match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => pt::circle_of(path).map(|c| (id, c)), + _ => None, + }; + if found.is_none() && why.is_none() { + why = Some(not_a_circle(d, id, editable(id))); + } + found }) - .collect() + .collect(); + (circles, why) }; + if let Some(why) = why { + return Err(bad(C, format!("select two or more circles to bridge: {why}"))); + } if circles.len() != roots.len() || circles.len() < 2 { return Err(bad(C, "select two or more circles to bridge")); } @@ -117,7 +130,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result { } beside.finish(d)?; } else { - // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + // Each shape's topmost circle becomes its outline (a plain path now) and the others go, + // with each group they leave empty. let mut gone = vec![]; for (members, outline) in shapes { let Some((&top, rest)) = members.split_last() else { continue }; @@ -128,7 +142,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result { made.push(top); gone.extend_from_slice(rest); } + let parents: Vec = gone.iter().filter_map(|id| d.parent_of(*id)).collect(); remove_each(d, &gone)?; + remove_emptied(d, parents)?; } sel.set(made.iter().chain(&alone).copied()); Ok(made) @@ -140,6 +156,60 @@ fn bridge(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The objects `ids` names, with each group among them (a clipping group excepted) as the objects +/// inside it, at any depth. +fn members(d: &Document, ids: &[NodeId]) -> Vec { + fn visit(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => out.push(n.id), + } + } + let mut out = vec![]; + for n in ids.iter().filter_map(|&id| d.node(id)) { + visit(n, &mut out); + } + out +} + +/// Why object `id`, which is not a circle the command bridges, is refused; `editable` says whether it can be +/// edited (not hidden or locked). +fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str { + // A pie spanning the whole turn, or none of it, is the whole ellipse. + let whole = |(start, end): (f64, f64)| { + let span = (end - start).rem_euclid(360.0); + span < 1e-9 || 360.0 - span < 1e-9 + }; + match d.node(id).map(|n| &n.kind) { + _ if !editable => "a selected object is hidden or locked", + // A transform that stretches an ellipse leaves its stored width and height as they were, so one stored with + // equal width and height gets the general message. + Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { w, h, pie, .. } if whole(pie) && w != h) => { + "an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height" + } + Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first", + _ => "a selected object is not a circle", + } +} + +/// Remove each of `parents` that is left with nothing in it, and then each group above it left with +/// nothing in it in turn. Layers stay. +fn remove_emptied(d: &mut Document, parents: Vec) -> Result<()> { + for parent in parents { + let mut at = Some(parent); + while let Some(id) = at { + match d.node(id) { + Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => { + at = d.parent_of(id); + d.remove(id)?; + } + _ => break, + } + } + } + Ok(()) +} + /// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 745f216b68..1f47454749 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -2,7 +2,7 @@ //! gap, many circles joined to their neighbors within reach, and what it refuses. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; use vectorcraft_geom::kurbo::Shape; use crate::Session; @@ -173,6 +173,50 @@ fn far_apart_nested_and_other_objects_are_refused() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); } +#[test] +fn a_refusal_says_why_an_object_is_not_a_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + // A hand-drawn ellipse 1 pt taller than wide. + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 80, "width": 40, "height": 41})).unwrap()["id"].as_u64().unwrap()); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let stretched = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("object.transform", &json!({"ids": [stretched.0], "matrix": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let e = err(&mut s, json!({"ids": [a.0, oval.0]})); + assert!( + e.ends_with( + "select two or more circles to bridge: an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height" + ), + "{e}" + ); + let e = err(&mut s, json!({"ids": [a.0, square.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}"); + // A circle stretched by a transform keeps its equal stored width and height, so it is not called unequal. + let equal = match s.doc().unwrap().doc.node(stretched).map(|n| &n.kind) { + Some(NodeKind::Path { live: Some(live), .. }) => matches!(**live, LiveShape::Ellipse { w, h, .. } if w == h), + _ => false, + }; + assert!(equal, "the stretched circle keeps a live ellipse of equal width and height"); + let e = err(&mut s, json!({"ids": [a.0, stretched.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}"); + let e = err(&mut s, json!({"ids": [a.0]})); + assert!(e.ends_with("select two or more circles to bridge"), "one circle: {e}"); + select(&mut s, &[b]); + s.execute("object.hide", &json!({})).unwrap(); + let e = err(&mut s, json!({"ids": [a.0, b.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is hidden or locked"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step for a refusal"); + + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = circle(&mut s, 300.0, 200.0, 20.0); + let e = err(&mut s, json!({"ids": [compound.0, c.0]})); + assert!(e.ends_with("select two or more circles to bridge: a compound path is not a circle: release it first"), "{e}"); +} + /// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100). fn grid(s: &mut Session) -> Vec { (0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect() @@ -329,6 +373,118 @@ fn an_id_given_twice_is_one_circle() { assert_eq!(top_level(&s), [b]); } +/// The objects directly inside `id`. +fn inside(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +fn make(s: &mut Session, command: &str, ids: &[NodeId]) -> NodeId { + select(s, ids); + NodeId(s.execute(command, &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn a_group_the_bridged_circles_leave_empty_goes_in_the_same_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [gb], "the lower circle's group, left empty, goes"); + assert_eq!(inside(&s, gb), [b], "the outline stays in the upper circle's group"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!((inside(&s, ga), inside(&s, gb)), (vec![a], vec![b])); + + // Kept circles leave their groups as they are. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!(inside(&s, ga), [a]); +} + +#[test] +fn groups_above_an_emptied_group_go_in_turn_and_a_group_with_other_objects_stays() { + let mut s = session(); + // a in a group that is all of another group; c in a group with a square; b on the layer. + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let c = circle(&mut s, 200.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let inner = make(&mut s, "object.group", &[a]); + let outer = make(&mut s, "object.group", &[inner]); + let gc = make(&mut s, "object.group", &[square, c]); + let layer = s.doc().unwrap().doc.layers[0].id; + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [c], "one shape, in the topmost circle's place"); + assert_eq!(top_level(&s), [gc], "both groups around a go, b goes from the layer"); + assert_eq!(inside(&s, gc), [c, square], "the group with the square stays"); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none() && d.node(outer).is_none()); + assert!(d.node(layer).is_some(), "the layer stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inside(&s, outer), [inner]); + assert_eq!(inside(&s, inner), [a]); +} + +#[test] +fn a_compound_path_the_bridged_circles_leave_empty_goes() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let compound = make(&mut s, "object.compoundPath.make", &[a]); + assert_eq!(inside(&s, compound), [a]); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(top_level(&s), [b]); + assert!(s.doc().unwrap().doc.node(compound).is_none()); +} + +#[test] +fn a_selected_group_of_grouped_circles_keeps_only_the_outlines_group() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let outer = make(&mut s, "object.group", &[ga, gb]); + select(&mut s, &[outer]); + s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(top_level(&s), [outer]); + assert_eq!(inside(&s, outer), [gb], "the lower circle's group goes, the outline's stays"); + assert_eq!(inside(&s, gb), [b]); +} + +#[test] +fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let c = circle(&mut s, 220.0, 100.0, 20.0); + // a below in the first layer, b and c in the sublayer: c's shape takes a's and b's places. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layers.iter().any(|l| l.id != upper && l.children().is_some_and(|c| c.is_empty())), "the emptied layer stays"); + assert_eq!(inside(&s, sub), [c]); + // The sublayer left with nothing in it stays too. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + s.execute("layer.setCurrent", &json!({"id": upper.0})).unwrap(); + let c = circle(&mut s, 220.0, 100.0, 20.0); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + assert_eq!(inside(&s, sub), Vec::::new(), "the emptied sublayer stays"); + assert_eq!(inside(&s, upper), [sub, c]); +} + #[test] fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { let mut s = session(); @@ -354,3 +510,60 @@ fn locked_and_hidden_circles_are_not_bridged() { s.execute("object.hide", &json!({})).unwrap(); assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); } + +fn group(s: &mut Session, ids: &[NodeId]) -> NodeId { + NodeId(s.execute("object.group", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap()["id"].as_u64().unwrap()) +} + +fn children(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn a_selected_group_of_circles_bridges_the_circles_inside_it() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let g = group(&mut s, &[a, b]); + select(&mut s, &[g]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(r["id"], json!(b.0), "two circles, joined in the upper one's place"); + assert_eq!(top_level(&s), [g]); + assert_eq!(children(&s, g), [b], "the outline stays in the group"); + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, g), [a, b]); + + // A group inside a group, given with one of its own circles, and a loose circle: three circles, so the reach + // applies. + let c = circle(&mut s, 300.0, 100.0, 20.0); + let outer = group(&mut s, &[g]); + let r = s.execute(BRIDGE, &json!({"ids": [outer.0, a.0, c.0], "reach": 30})).unwrap(); + assert_eq!(r["ids"], json!([b.0]), "the grouped circles are joined"); + assert_eq!(r["alone"], json!([c.0]), "the far circle is out of reach"); +} + +#[test] +fn a_selected_group_with_other_objects_or_a_clipping_group_is_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let g = group(&mut s, &[a, b, square]); + let steps = s.doc().unwrap().history.undo.len(); + assert!(err(&mut s, json!({"ids": [g.0]})).contains("select two or more circles to bridge")); + assert_eq!(children(&s, g), [a, b, square]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); + + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let mask = circle(&mut s, 130.0, 100.0, 80.0); + select(&mut s, &[a, b, mask]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + assert!(err(&mut s, json!({"ids": [clip.0]})).contains("select two or more circles to bridge")); + assert_eq!(top_level(&s), before); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e47c009062..372ceb6e12 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}", has_selection, common_tangents )] @@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError { ) } +/// The parameters that shape a curved bridge. +const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"]; + fn common_tangents(s: &mut Session, p: &Value) -> Result { const C: &str = COMMON_TANGENTS; - let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let kinds = choice(p, C, "tangents", &KINDS)?; + let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None }; + if switch_or(p, "curved", false, C)? { + if kinds.is_some_and(|k| k != "external") { + return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out")); + } + if given("centerline") { + return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`")); + } + if connect == Some(false) { + return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true")); + } + // The outline is Smooth Bridge's. + let mut bridged = serde_json::Map::new(); + for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) { + bridged.insert((*key).to_owned(), p[*key].clone()); + } + return super::bridge::bridge(s, &Value::Object(bridged)); + } + if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) { + return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it"))); + } + let kinds = kinds.unwrap_or("all"); + let connect = connect.unwrap_or(false); let centerline = switch_or(p, "centerline", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; @@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + // With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed + // shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind. + let shapes: Vec<(Vec, bool)> = if connect { + let mut out = vec![]; + for kind in [pt::TangentKind::External, pt::TangentKind::Internal] { + let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect(); + match of.as_slice() { + [l, m] => { + // A point's two lines share the point, which then closes the ring once. + let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size()); + let mut ring = vec![l.from, l.to, m.to, m.from]; + ring.dedup_by(|q, p| same(*q, *p)); + if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) { + ring.pop(); + } + out.push((ring, true)); + } + _ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))), + } + if point { + break; + } + } + out + } else { + lines.iter().map(|&(from, to)| (vec![from, to], false)).collect() + }; if lines.is_empty() && point { // Written as `EngineError::Other` so that the i18n message scan finds it. let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); @@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; let mut ids = vec![]; let mut center_id = None; - for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let center = center.map(|(from, to)| (vec![from, to], false)); + for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() { let id = d.alloc_id(); - let path = PathData::single(SubPath::polyline(&[from, to], false)); + let path = PathData::single(SubPath::polyline(&points, closed)); let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); look.apply(d, &mut n); d.insert(parent, idx + 1 + k, n)?; - if k == lines.len() { + if k == shapes.len() { center_id = Some(id); } ids.push(id); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 7ab6b32838..1653089520 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -354,3 +354,113 @@ fn bad_selections_and_params_are_refused() { let g = group_of(&mut s, &[b]); assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); } + +/// The one closed outline of path `id`. +fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) }; + assert!(sp.closed); + sp.clone() +} + +/// The anchors of path `id`'s one closed outline. +fn corners(s: &Session, id: NodeId) -> Vec { + outline(s, id).anchors.iter().map(|a| a.p).collect() +} + +#[test] +fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap(); + assert_eq!(steps(&s), before + 1, "one undo step"); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one shape in place of two lines"); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay"); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 4); + // The tangents above and below both circles, joined by each circle's vertical diameter. + for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { + assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); + } + // In order around the band, not crossing itself: the area is the 100 by 40 rectangle's. + let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::() / 2.0; + assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +#[test] +fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() { + let mut s = session(); + let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0)); + let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1)); + let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline"); + for &id in &ids[..2] { + let found = corners(&s, id); + assert_eq!(found.len(), 4); + let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count(); + assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}"); + } + assert_ne!(corners(&s, ids[0]), corners(&s, ids[1])); + assert_eq!(r["centerline"], json!(ids[2].0)); + + let mut s = session(); + let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0)); + let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}"); + assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0)))); +} + +#[test] +fn curved_makes_the_bridge_the_smooth_bridge_command_makes() { + let build = || { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)]; + select(&mut s, &ids); + s + }; + for (merged, old) in [ + (json!({"curved": true}), json!({})), + ( + json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}), + json!({"gap": 5, "reach": 30, "keepOriginals": true}), + ), + ] { + let (mut s, mut t) = (build(), build()); + let r = s.execute(C, &merged).unwrap(); + let q = t.execute("addon.pathtools.bridge", &old).unwrap(); + assert_eq!(r, q, "{merged}"); + let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::>(); + assert_eq!(kinds(&s), kinds(&t), "{merged}"); + } +} + +#[test] +fn options_of_the_other_mode_are_refused() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + select(&mut s, &[a, b]); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + for (p, says) in [ + (json!({"connect": "yes"}), "connect"), + (json!({"curved": true, "tangents": "all"}), "external"), + (json!({"curved": true, "centerline": true}), "centerline"), + (json!({"curved": true, "connect": false}), "connected"), + (json!({"radius": 50}), "curved"), + (json!({"connect": true, "keepOriginals": true}), "curved"), + (json!({"curved": true, "radius": 50, "gap": 2}), "not both"), + (json!({"curved": true, "radius": 0}), "radius"), + ] { + assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone())); + } + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 584f33dc36..1b16421c8d 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -237,6 +237,7 @@ fn add_points_splits_selected_segments_evenly() { let n = steps(&s); assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3)); let xs: Vec = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect(); + assert_eq!(xs.len(), 5, "{xs:?}"); assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}"); assert_eq!(steps(&s), n + 1); refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]); diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index c9ae29a303..e99294a4b0 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,17 +1,19 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects //! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by //! Link Status selects the images and placed documents whose file is linked, embedded, missing or -//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins -//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. +//! modified (#5526), saying which ones it had to leave out and why. Edit Points Only narrows the +//! selection to the anchor points selected in it, dropping selected segments and objects without +//! anchor points. Its submenu (Object › Plug-ins › Selection Tools), the Links panel's menu items +//! and the dialogs are the UI's. #[cfg(test)] mod tests; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::{AnchorRef, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point}; use super::super::links::{Status, statuses}; use super::super::panelcmds::listed_artboards; @@ -47,6 +49,15 @@ pub fn specs() -> Vec { has_doc, by_link_status ), + cmd!( + "addon.select.editPointsOnly", + "Edit Points Only", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step. In the desktop dialog, a successful preview or OK clears only that dialog's preview error if it is still the current status message → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + has_doc, + edit_points_only + ), ] } @@ -193,3 +204,114 @@ fn by_link_status(s: &mut Session, p: &Value) -> Result { } Ok(out) } + +/// The anchor points of `path` that `refs` names, leaving out references to points it does not have. +fn on_path(path: &PathData, refs: &BTreeSet) -> BTreeSet { + refs.iter().copied().filter(|&(si, ai)| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())).collect() +} + +/// The points at the ends of the segments `segments` of `path`. +fn segment_ends(path: &PathData, segments: &BTreeSet) -> BTreeSet { + let mut ends = BTreeSet::new(); + for &(si, seg) in segments { + if let Some(sp) = path.subpaths.get(si) { + ends.extend([(si, seg), (si, (seg + 1) % sp.anchors.len().max(1))]); + } + } + ends +} + +/// The paths inside container `n` with at least one anchor point, depth first, through the groups +/// and compound paths in it: hidden and locked objects (and what they hold), a Shaper Group's +/// original shapes, and paths made into guides while `guides_locked`, are left out. +fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) { + let originals = usize::from(n.extras().shaper.is_some()); + for c in n.children().into_iter().flatten().skip(originals) { + if !c.visible || c.locked { + continue; + } + match &c.kind { + NodeKind::Path { guide: true, .. } if guides_locked => {} + NodeKind::Path { path, .. } if path.anchors().next().is_some() => out.push(c), + NodeKind::Group { .. } | NodeKind::Compound { .. } => paths_inside(c, guides_locked, out), + _ => {} + } + } +} + +/// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it. +fn edit_points_only(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.editPointsOnly"; + let keep_ends = match p.get("segmentEnds") { + None => false, + Some(value) => value.as_bool().ok_or_else(|| bad(C, "`segmentEnds` must be true or false"))?, + }; + let guides_locked = s.menu.guides_locked; + let st = s.doc()?; + let (doc, sel) = (&st.doc, &st.selection); + if sel.objects.is_empty() { + return Err(bad(C, "select anchor points or segments first")); + } + // Each path once, in selection order, with its points kept: `None` for all of them. + let mut seen = HashSet::new(); + let explicit: HashSet = sel.objects.iter().copied().filter(|id| sel.anchors.contains_key(id)).collect(); + let mut kept: Vec<(NodeId, usize, Option>)> = vec![]; + for id in &sel.objects { + let Some(n) = doc.node(*id) else { continue }; + if !doc.ancestry(*id).is_some_and(|ancestors| ancestors.iter().all(|id| doc.node(*id).is_some_and(|n| n.visible && !n.locked))) { + continue; + } + match &n.kind { + NodeKind::Path { path, .. } => { + let Some(refs) = sel.anchors.get(id) else { + let count = path.anchors().count(); + if count > 0 && seen.insert(*id) { + kept.push((*id, count, None)); + } + continue; + }; + let mut picked = on_path(path, refs); + if let Some(segments) = sel.segments.get(id) + && !keep_ends + { + let ends = segment_ends(path, segments); + picked.retain(|r| !ends.contains(r)); + } + if !picked.is_empty() && seen.insert(*id) { + kept.push((*id, picked.len(), Some(picked))); + } + } + NodeKind::Group { .. } | NodeKind::Compound { .. } => { + let mut inside = vec![]; + paths_inside(n, guides_locked, &mut inside); + for c in inside { + if explicit.contains(&c.id) { + continue; + } + if seen.insert(c.id) { + kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None)); + } + } + } + _ => {} + } + } + let points: usize = kept.iter().map(|(_, n, _)| n).sum(); + let objects: Vec = kept.iter().map(|(id, ..)| *id).collect(); + let anchors: BTreeMap> = kept.into_iter().filter_map(|(id, _, set)| Some((id, set?))).collect(); + if objects.is_empty() { + return Err(bad(C, "no anchor points are selected")); + } + let changed = objects != sel.objects || anchors != sel.anchors || !sel.segments.is_empty() || !sel.guides.is_empty(); + let count = objects.len(); + if changed { + s.select(|_, sel| { + let (key, key_anchor) = (sel.key.filter(|k| objects.contains(k)), sel.key_anchor); + sel.set(objects); + sel.anchors = anchors; + sel.key = key; + sel.key_anchor = key_anchor; + })?; + } + Ok(json!({ "changed": changed, "count": count, "points": points })) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 09106a3652..4b86ae5802 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -337,3 +337,320 @@ mod by_link_status { assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); } } + +/// Edit Points Only. +mod edit_points_only { + use std::collections::{BTreeMap, BTreeSet}; + + use serde_json::{Value, json}; + use vectorcraft_doc::NodeId; + + use super::rect; + use crate::Session; + + const C: &str = "addon.select.editPointsOnly"; + + /// A document with two rectangles, `a` and `b` (four anchors each, anchor 0 first). + fn two() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 100.0, 10.0, 50.0, 50.0); + (s, a, b) + } + + /// Anchors 0 and 1 of `a`, anchor 3 of `b`, and then segment 1 of `b` (its ends are anchors 1 and 2). + fn mixed(s: &mut Session, a: NodeId, b: NodeId) { + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + s.execute("select.anchorsMany", &json!({"items": items})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + } + + fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() + } + + /// Selected objects, with the selected anchors of those selected in part. + type Picked = (Vec, BTreeMap>); + + /// The selected objects and their selected anchors. + fn picked(s: &Session) -> Picked { + let sel = &s.doc().unwrap().selection; + (sel.objects.clone(), sel.anchors.clone()) + } + + #[test] + fn selected_segments_drop_out_and_the_anchor_points_stay() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)]), "a segment's ends move with it"); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 3})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![a, b]); + assert_eq!(sel.anchors[&a], refs(&[(0, 0), (0, 1)])); + assert_eq!(sel.anchors[&b], refs(&[(0, 3)]), "the segment's ends leave the selection"); + assert!(sel.segments.is_empty(), "no segment stays selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn segment_ends_stay_as_anchor_points_when_asked() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let r = s.execute(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 5})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)])); + assert!(sel.segments.is_empty()); + // With the default, a path holding only a selected segment leaves the selection. + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + let r = s.execute(C, &json!({"segmentEnds": false})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 1, "points": 1})); + assert_eq!(picked(&s), (vec![a], BTreeMap::from([(a, refs(&[(0, 2)]))]))); + } + + #[test] + fn a_selection_of_anchor_points_alone_is_left_as_it_is() { + let (mut s, a, b) = two(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]]})).unwrap(); + let before = picked(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 1, "points": 2})); + assert_eq!(picked(&s), before); + // Paths selected whole keep all their points. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 2, "points": 8})); + assert_eq!(picked(&s), (vec![a, b], BTreeMap::new())); + } + + #[test] + fn explicit_anchor_picks_override_group_expansion_in_either_order() { + for group_first in [true, false] { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| { + sel.set(if group_first { vec![group, a] } else { vec![a, group] }); + sel.anchors.insert(a, refs(&[(0, 0)])); + }) + .unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().clone(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 2, "points": 5})); + assert_eq!(s.doc().unwrap().selection.anchors[&a], refs(&[(0, 0)])); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + let after = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap(); + for ((_, i, old), (_, _, new)) in before.anchors().zip(after.anchors()) { + if i == 0 { + assert_ne!(new.p, old.p); + } else { + assert_eq!(new.p, old.p, "unselected anchors stay in place"); + } + } + } + } + + #[test] + fn hidden_or_locked_selected_nodes_and_their_ancestors_are_left_out() { + for locked in [false, true] { + for target in ["path", "group", "ancestor", "layer"] { + let (mut s, a, b) = two(); + let good = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let blocked = match target { + "path" => a, + "layer" => s.doc().unwrap().doc.layers[0].id, + _ => group, + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let node = doc.node_mut(blocked).unwrap(); + if locked { + node.locked = true; + } else { + node.visible = false; + } + let selected = if matches!(target, "path" | "ancestor") { a } else { group }; + s.execute("select.set", &json!({"ids": [good.0, selected.0]})).unwrap(); + if target == "layer" { + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &json!({})).is_err()); + assert_eq!(s.doc().unwrap().selection, before); + } else { + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (vec![good], BTreeMap::new()), "{target}, locked: {locked}"); + } + } + } + } + + #[test] + fn group_expansion_selects_each_descendant_path() { + let (mut s, _, _) = two(); + let mut groups = vec![]; + let mut paths = vec![]; + for x in [10.0, 100.0, 200.0] { + let a = rect(&mut s, x, 100.0, 20.0, 20.0); + let b = rect(&mut s, x, 150.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + groups.push(NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())); + paths.extend([a, b]); + } + s.select(|_, sel| sel.set(groups)).unwrap(); + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (paths, BTreeMap::new())); + } + + #[test] + fn appearance_row_commands_survive_preview_replacement_and_cancel() { + for index in [json!(1), Value::Null] { + for selection_preview in [false, true] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = !selection_preview; + if selection_preview { + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + } else { + s.preview("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + let expected = index.as_u64().map(|i| i as usize); + s.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(s.appearance_item(), expected, "replacement preserves the explicit row command"); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), expected, "cancel preserves the explicit row command"); + } + } + } + + #[test] + fn cancel_preserves_an_appearance_row_command_without_another_preview() { + for index in [json!(1), Value::Null] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.preview(C, &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), index.as_u64().map(|i| i as usize)); + } + } + + #[test] + fn canceling_a_selection_preview_restores_the_active_appearance_item() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.items.clone(); + s.begin_interaction("Edit Points Only").unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + s.preview(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(s.appearance_item(), None); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), Some(0)); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let after = &s.doc().unwrap().doc.node(a).unwrap().appearance.items; + assert_ne!(after[0], before[0]); + assert_eq!(&after[1..], &before[1..]); + } + + #[test] + fn whole_paths_keep_object_transforms_and_stroke_scaling() { + let (mut s, a, _) = two(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width(); + s.execute(C, &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.contains_key(&a)); + s.execute("object.transform", &json!({"matrix": [2, 0, 0, 2, 0, 0], "strokes": true})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width() > before); + } + + #[test] + fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() { + let (mut s, a, b) = two(); + let c = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + let hidden = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, c.0, hidden.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let d = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, d.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects.clone(); + assert_eq!(compound.len(), 1); + let members: Vec = s.doc().unwrap().doc.node(compound[0]).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + assert_eq!(members.len(), 2); + s.execute("select.set", &json!({"ids": [compound[0].0, group]})).unwrap(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 4, "points": 16}), "{r}"); + let mut want = members; + want.extend([b, c]); + assert_eq!(picked(&s), (want, BTreeMap::new()), "the hidden path and the type are left out"); + } + + #[test] + fn guide_paths_in_a_group_are_left_out_while_guides_are_locked() { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + s.execute("select.set", &json!({"ids": [a.0, group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![a], BTreeMap::new())); + // Unlocked, the guide path is a path like any other. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![b], BTreeMap::new())); + } + + #[test] + fn nothing_to_keep_is_an_error_that_leaves_the_selection() { + let (mut s, a, b) = two(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(C, &json!({})).is_err(), "nothing selected"); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.add", &json!({"ids": [text.0]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + for p in [ + json!({"segmentEnds": null}), + json!({"segmentEnds": "yes"}), + json!({"segmentEnds": 1}), + json!({"segmentEnds": [true]}), + json!({"segmentEnd": true}), + ] { + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection, before, "{p}"); + } + assert!(Session::new().execute(C, &Value::Null).is_err(), "without a document"); + } +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index a8518719be..148ccd4b9a 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -69,7 +69,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live"); s.execute("edit.undo", &json!({})).unwrap(); - assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone"); + let undone: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); + assert_eq!(undone, [('a', 20.0), ('b', 20.0), (' ', 20.0), ('c', 20.0), ('d', 20.0)], "undone"); } #[test] diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index d319e0d2a4..a530efce99 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -139,7 +139,7 @@ pub fn specs() -> Vec { "Select Appearance Item", [], None, - "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it → {index}", + "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it. A row set or cleared outside a drag's preview stays set or cleared when the preview is replaced or canceled → {index}", has_selection, set_active_item ), @@ -174,7 +174,7 @@ pub fn specs() -> Vec { } /// The Appearance panel's active row, remembered for the selection it was chosen in. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ActiveItem { doc: u64, objects: Vec, @@ -956,6 +956,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let index = match p.get("index") { Some(Value::Null) => { s.active_appearance_item = None; + clear_preview_item(s); return Ok(json!({ "index": Value::Null })); } Some(_) => index_param(p, "index", C)?, @@ -968,9 +969,21 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let doc = st.uid; s.fill_active = fill; s.active_appearance_item = Some(ActiveItem { doc, objects, index }); + clear_preview_item(s); Ok(json!({ "index": index })) } +fn clear_preview_item(s: &mut Session) { + if !s.previewing { + if let Some(it) = s.active_mut().and_then(|st| st.interaction.as_mut()) { + it.active_appearance_item = None; + } + if let Some(held) = &mut s.held_interaction { + held.interaction.active_appearance_item = None; + } + } +} + fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" }; let mut ids = row_targets(s, p, cmd)?; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index bd6cb220e5..ee2b1904f6 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Apply Brush", [], None, - "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current → {ids}", + "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; the brush settings of each path's top stroke (brush.objectOptions) are cleared, and clearing them is one undo step; when the brush is already current and applying it leaves every path as it was (its top stroke already has the brush, paint, a width above 0 and no settings of its own), nothing changes and no undo step is recorded → {ids}", has_doc, brush_apply ), @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update); params and a newName that leave the brush as it is change nothing and record no undo step → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index af71b2dae9..eaebecf11e 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result { } let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); let stroke = stroke_paint(s); - s.edit("Apply Brush", |d, _| { + crate::cmd::colorcmds::edit_if_changed(s, "Apply Brush", |before, d| { d.unknown.insert(brush::CURRENT_KEY.into(), json!(name)); apply_brush(d, &ids, &name, &stroke); - Ok(()) + let changed = brush::current(before).as_deref() != Some(name.as_str()) || ids.iter().any(|id| before.node(*id) != d.node(*id)); + Ok(((), changed)) })?; Ok(json!({ "ids": ids_json(&ids) })) } @@ -213,6 +214,7 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt } } +/// Stores `lib` and applies `renames` as one undo step named `label`. fn save_library(s: &mut Session, label: &str, mut lib: Vec, renames: &[(String, Option)]) -> Result<()> { s.edit(label, |d, _| { for (from, to) in renames { @@ -503,8 +505,13 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { v["name"] = json!(name); } v["type"] = json!(lib[i].kind.type_id()); - lib[i] = parse_brush(C, v)?; - let out = lib[i].name.clone(); + let edited = parse_brush(C, v)?; + let out = edited.name.clone(); + // Options that leave the brush as it is change nothing and add no undo step. + if new_name.is_none() && edited == lib[i] { + return Ok(json!({ "name": out })); + } + lib[i] = edited; let rename = new_name.map(|nn| (name, Some(nn))); save_library(s, "Brush Options", lib, rename.as_slice())?; Ok(json!({ "name": out })) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 426f374a5c..21618367b6 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Merge", ["Object", "Live Paint"], None, - "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_multi_or_ids, lp_merge ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step). The command stops with an error and leaves the art unchanged when a group's paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when detect is on. → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -740,12 +740,13 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option { - let (regs, edges, _) = po::live_paint_with_gaps(&shapes, gap); + let (regs, edges, _) = po::try_live_paint_with_gaps(&shapes, gap).map_err(too_many)?; (regs, edges) } - None => po::live_paint(&shapes), + None => po::try_live_paint(&shapes).map_err(too_many)?, }; if regs.is_empty() && edges.is_empty() { return Err(EngineError::Other("Live Paint: these paths are too degenerate to paint".into())); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 693608574e..a4e2892f39 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1586,6 +1586,8 @@ mod trace_limit_tests { // anchors each. let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(!outlined.strokes.is_empty(), "{res:?}"); + assert_eq!(outlined.strokes.len(), all.as_ref().unwrap().strokes.len(), "one outline for each seam fill: {outlined:?}"); assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); let n = strokes(all.as_ref().unwrap()); assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 610498f56a..20cb4c96ab 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -696,9 +696,13 @@ mod tests { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); assert_eq!(c, layer, "the scenario needs the id to be reused"); s.execute("edit.paste", &json!({})).unwrap(); - let d = &s.doc().unwrap().doc; + let st = s.doc().unwrap(); + let d = &st.doc; let compound = d.node(NodeId(c)).unwrap(); - assert!(compound.children().unwrap().iter().all(|ch| matches!(ch.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(compound.children().unwrap().len(), 1, "the compound path holds only the rectangle it was made from"); + let pasted = st.selection.objects.clone(); + assert_eq!(pasted.len(), 1); + assert!(d.parent_of(pasted[0]).is_some_and(|p| d.node(p).unwrap().is_layer()), "the copy lands on a layer"); } #[test] diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index dc36e24380..1c8817c0e1 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Nudge in Perspective", [], None, - "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), copy?: bool} move the selection in perspective by the keyboard increment, as the arrow keys do with the Perspective Selection tool → {ids}", + "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool} move the selection in perspective by the keyboard increment (Snap to Grid doesn't apply), as the arrow keys do with the Perspective Selection tool → {ids}", has_selection, persp_nudge ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 6589fd3468..3f100acc5a 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -563,13 +563,16 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { Ok(json!({ "plane": plane.id(), "offset": depth })) } +/// `perspective.nudge`, the arrow keys with the Perspective Selection tool: the selection moves +/// within its plane by [`nudge_step`](crate::cmd::object::nudge_step), measured on the page at the +/// centre of its perspective box, without Snap to Grid. pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { const C: &str = "perspective.nudge"; let (dx, dy) = (number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) { return Err(bad(C, "dx and dy give the arrow's direction")); } - let k = s.prefs.keyboard_increment * if switch_or(p, "big", false, C)? { 10.0 } else { 1.0 }; + let k = crate::cmd::object::nudge_step(s.prefs.keyboard_increment, switch_or(p, "big", false, C)?, switch_or(p, "fine", false, C)?); let copy = switch_or(p, "copy", false, C)?; let ids = selected_roots(s)?; // The step is measured on the page at the centre of the selection's perspective box. @@ -578,7 +581,12 @@ pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?; let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?; let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k; - persp_move(s, &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy})) + // The arrow keys move by the step: Snap to Grid would pull an edge on a gridline back onto it, + // so a nudge smaller than a quarter cell would move nothing. + persp_move( + s, + &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "snap": false}), + ) } pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index ef9cd71850..c1cb80c939 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1722,7 +1722,7 @@ mod tests { let jags = polyline(&ring); let sp = SubPath::new(jags.clone(), true); assert!(subpath_len(&sp) < 24.0); - assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor"); + assert_eq!(smooth_corners(&jags, true, 1e-6), vec![true; 16], "each jag turns sharply at its anchor"); assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..d9b6e25b96 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -39,6 +39,15 @@ pub fn specs() -> Vec { has_doc, doc_move ), + cmd!( + "document.setSaved", + "Set Saved State", + [], + None, + "{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is", + has_doc, + doc_set_saved + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -162,7 +171,7 @@ pub fn specs() -> Vec { "Cut", ["Edit"], Some("Cmd+X"), - "{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected", + "{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected", has_selection_guides_or_artboard_tool, cut ), @@ -171,7 +180,7 @@ pub fn specs() -> Vec { "Copy", ["Edit"], Some("Cmd+C"), - "{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", + "{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", has_selection_guides_or_artboard_tool, copy ), @@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_set_saved(s: &mut Session, p: &Value) -> Result { + const C: &str = "document.setSaved"; + let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let saved = match p.get("saved") { + None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")), + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(C, "`saved` must be true or false")), + }; + let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?; + let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?; + if st.is_dirty() == saved { + if saved { + st.mark_saved(); + } else { + st.mark_unsaved(); + } + } + ok() +} + fn doc_move(s: &mut Session, p: &Value) -> Result { let n = s.documents().len(); let from = match p.get("from") { @@ -967,7 +996,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { } #[cfg(test)] ROOTS_FOUND.set(ROOTS_FOUND.get() + 1); - let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc)); + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let roots = roots_placed(&st.doc, ids, &paths, |_, _| false); *kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone())); roots }) @@ -1015,7 +1045,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> { pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { refuse_symbol_part(s)?; let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true)) + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + Ok(roots_placed(&st.doc, ids, &paths, |_, _| true)) +} + +/// The objects of `objects` that are in `doc`, in paint order as +/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One +/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after +/// `in_paint_order` walks the tree twice). +fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec, HashMap>) { + let paths = doc.index_paths(objects.iter().copied()); + let mut ids: Vec = objects.iter().copied().filter(|id| paths.contains_key(id)).collect(); + ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b))); + (ids, paths) } /// [`selected_roots`] for the selected objects inside the isolated object `root` @@ -1027,8 +1069,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { refuse_symbol_part(s)?; let st = s.doc()?; - let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); - Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root)) + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their @@ -1042,6 +1085,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { fn roots_within(doc: &Document, ids: Vec, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); + roots_placed(doc, ids, &paths, keep_member) +} + +/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already. +fn roots_placed(doc: &Document, ids: Vec, paths: &HashMap>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // A compound-path member acts as its compound (compounds are one object). let mut sel: Vec<(NodeId, Option>)> = ids .into_iter() @@ -1105,7 +1153,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m))) }) }; - let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound)); + let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects); + let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound)); Ok((direct, roots)) } @@ -1163,6 +1212,13 @@ fn copy(s: &mut Session, p: &Value) -> Result { }); clip.source_artboard = board.map(|a| a.rect); } + if let Some(value) = p.get("artboard") { + let board = value + .as_u64() + .and_then(|v| st.doc.artboards.get(index(v))) + .ok_or_else(|| bad("edit.copy", "`artboard` must be the index of an artboard of the document"))?; + clip.source_artboard = Some(board.rect); + } clip.guides = guides; s.clipboard = clip; Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 7ac2d9c162..7e0471f0f5 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -348,6 +348,36 @@ fn direct_selection_cut_timing() { } } +/// Finding the selected roots (for the menus, for Move and its siblings, for Copy and Cut, and +/// inside an isolated group) walks the tree once for the paint order and the roots together, in +/// paint order whatever order the objects were selected in. +#[test] +fn finding_the_selected_roots_walks_the_tree_once() { + let mut s = session(2_000, square); + let all = crate::tests_large_edits::layer(&s, 0); + let reversed: Vec = all.iter().rev().map(|id| id.0).collect(); + s.execute("select.set", &json!({"ids": reversed})).unwrap(); + type Find = fn(&Session) -> Vec; + let finds: [(&str, Find); 3] = [ + ("the selected roots", |s| selected_roots(s).unwrap()), + ("the roots to transform", |s| selected_roots_to_transform(s).unwrap()), + ("Copy's targets", |s| copy_cut_targets(s).unwrap().1), + ]; + for (what, find) in finds { + let walks = tree_walks(); + assert!(find(&s) == all, "{what} in paint order"); + assert_eq!(tree_walks() - walks, 1, "finding {what} walked the tree {} times", tree_walks() - walks); + } + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + s.execute("select.set", &json!({"ids": reversed})).unwrap(); + // The first call also builds the lookup cache that the isolation check reads. + assert!(selected_roots_inside(&s, group, false).unwrap() == all, "the roots inside the group in paint order"); + let walks = tree_walks(); + assert!(selected_roots_inside(&s, group, false).unwrap() == all); + assert_eq!(tree_walks() - walks, 1, "finding the roots inside the group walked the tree {} times", tree_walks() - walks); +} + /// The selected roots are found once for a document version and its selected objects, however many enabled checks /// read them, and found again after the selection changes, after an edit, and for another selection. #[test] diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 5f66067142..38654bb8ba 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -125,6 +125,13 @@ pub use screens::{ builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list, preset_rows as screen_preset_rows, }; +pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing}; + +/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file, +/// which holds the artboards its own options pick? An unknown version counts as one. +pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool { + format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true)) +} pub use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. @@ -141,6 +148,8 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE}; pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8ca1fedcd7..84b8bc1a4f 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +/// The most a file read during a script command holds, the limit an importer reads. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES; +/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { + use std::io::Read; may_read(path)?; // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); } - std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + if crate::file_access::in_script_command() { + let max = SCRIPT_OPEN_MAX_BYTES; + let read = || -> std::io::Result> { + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::other("not a file")); + } + if meta.len() > max as u64 { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + let mut bytes = Vec::new(); + file.take(max as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > max { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + Ok(bytes) + }; + read().map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } else { + std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } } /// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a48ac3e85b..e902f4185a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -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|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", + "{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, units, 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 ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", has_doc, screens::export_for_screens ), diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 5f2c14bfd5..48a8c828ab 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -73,7 +73,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator, key: im /// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}` /// (`files`: every file when there are several; `linked`: the images it links to); with no path -/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. +/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is +/// checked against the file access in force before the first file is written, so a refused path +/// writes none of them. pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result { let files = enc.named(doc, path.unwrap_or(name)); let (main, linked) = files.split_at(enc.files.len()); @@ -82,6 +84,12 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), }; if path.is_some() { + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + super::may_write(p)?; + } + } for (p, bytes) in &files { write_file(p, bytes)?; } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4f11935db0..cce50485dd 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -818,7 +818,7 @@ pub fn read_for_open_asking( (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode), // The color mode `p` asks for converts the colors after the policies did, through the // profiles the document keeps. None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), @@ -1096,6 +1096,21 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result { source(p, "document.open")? } }; + let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"])); + if crate::file_access::in_script_command() && (options || aliases) { + // An importer plug-in receives only the params, so it cannot apply the pages or the crop + // box; `linkPages` reads the file with the built-in reader before any importer. + let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true); + let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none(); + let pdf = built_in + && (!options + || (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) + && !vectorcraft_pdf::is_postscript(&src.bytes))); + if !pdf { + return Err(bad("document.open", "PDF open options require a PDF file")); + } + } // A relative path is the file in the working directory: its folder is where relative links // are found (a bare file name has no folder of its own). let path = src.path.map(super::absolute_path); diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 8ffb3f8133..954a345ae0 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -22,6 +22,8 @@ pub struct LoadOptions { pub pages: Option, /// The box each page's artboard (or placed frame) gets. pub crop: CropTo, + /// Whether the options explicitly request the crop box. + pub explicit_crop_box: bool, /// The password of an encrypted PDF. pub password: Option, /// The colour mode the document opens in, its colours converted as Document Color Mode does @@ -67,6 +69,7 @@ impl Default for LoadOptions { Self { pages: None, crop: CropTo::default(), + explicit_crop_box: false, password: None, color_mode: None, grays: Grays::default(), @@ -147,6 +150,7 @@ impl LoadOptions { Ok(Self { pages, crop, + explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(), password, color_mode, grays, @@ -173,14 +177,14 @@ impl LoadOptions { } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, - /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). + /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); + let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 7585861e9b..af84199414 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,7 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + redact_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option>()) { return Ok(stopped); } + // Every path is checked against the file access in force before the first file is + // written. A refused file is not handed to `write`, so a writer that does not check the + // file access writes none of the files; the error is the file access's own refusal, as + // the writers that check it give. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 + && let Some(refused) = files + .iter() + .find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })) + { + return Err(refused); + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1229,9 +1243,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; + let mut job = save_job(s, plan)?; let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + job.redact_paths = !given; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) @@ -1373,7 +1388,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), 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), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), 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), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 0fb1cc0860..4cc3cad433 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1131,23 +1131,29 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { /// The document the file of `item` that row `r` writes carries when it carries one /// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a -/// native, `.ai` or EPS row ([`board_document`]), else the item's document. -fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. `grown`: Include Bleed +/// grew the artboards by the document's bleed. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>, grown: bool) -> std::borrow::Cow<'a, Document> { match (&item.every_artboard, r.format.id, single) { (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), - _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item, grown)), _ => std::borrow::Cow::Borrowed(&*item.doc), } } /// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with -/// its background color and the art on it, as Save's separateArtboards writes it (#3868). -fn board_document(item: &Item) -> Document { +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). When +/// Include Bleed grew the artboard (`grown`), the artboard already holds the bleed, so the document +/// is written with a bleed of 0: opened again, its pages are not grown by the bleed a second time. +fn board_document(item: &Item, grown: bool) -> Document { let mut d = single_artboard(&item.doc, item.region, &item.name); if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { a.color = from.color; } super::save::keep_art_on(&mut d, item.region); + if grown && item.every_artboard.is_none() { + d.setup.bleed = [0.0; 4]; + } d } @@ -1209,7 +1215,7 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); let board = item.artboard.filter(|_| !all && r.whole_document()); if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) - && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref(), ungrown.is_some()), base) { return Err(bad(C, super::access::IMAGE_OUTSIDE)); } @@ -1402,7 +1408,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); + let d = board_docs + .entry((Arc::as_ptr(&item.doc) as usize, b)) + .or_insert_with(|| Arc::new(board_document(item, pdf_doc.is_some()))) + .clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 066c6fc63f..7a6547890f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -50,6 +50,12 @@ pub const OPTIONS: &[FormatOption] = &[ FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, + FormatOption { + name: "units", + ty: "string", + default: "null", + description: "override the document unit for width and height: px (bare numbers, one per point) | pt | mm | cm | in; omit to follow the document unit, not null (the viewBox stays in points; not with responsive)", + }, FormatOption { name: "preserveEditing", ty: "boolean", @@ -121,7 +127,7 @@ pub fn options_map(p: &Value) -> Result, String> { let mut m = Map::new(); let Some(o) = p.as_object() else { return Ok(m) }; for opt in OPTIONS.iter().filter(|opt| opt.name != "svg") { - if let Some(v) = o.get(opt.name).filter(|v| !v.is_null()) { + if let Some(v) = o.get(opt.name).filter(|v| opt.name == "units" || !v.is_null()) { m.insert(opt.name.into(), v.clone()); } } @@ -172,14 +178,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option Option { +pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option { let n = doc.artboards.len(); - let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing); - (n > 1 && !preserved).then(|| { + (n > 1 && !preserves_editing(doc, p)).then(|| { format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.") }) } +/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native +/// document (Preserve Editing Capabilities), which keeps every artboard. +pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool { + plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing) +} + /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index d27166e5da..1ef846806e 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -120,6 +120,10 @@ fn palette_exports_take_the_transparency_dither() { let dithered = file(json!({"transparencyDither": method})); let [left, right] = opaque_halves(&dithered); assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if method == "pattern" { + // The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%. + assert_eq!([left, right], [0.25, 0.75], "{format}"); + } assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file"); // Without transparency the dither does nothing. let opaque = file(json!({"transparencyDither": method, "transparency": false})); diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 74356b6f31..93c4d7e6b1 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1512,3 +1512,39 @@ fn each_piece_writes_its_own_native_document() { assert!(name.contains(&board), "{name} holds the artboard {board}"); } } + +/// With Include Bleed, a native, `.ai` or EPS file of an artboard holds the artboard grown by the +/// bleed, and no bleed of its own: opened again, a PDF with the document's bleed has the same page +/// as the export's own PDF row, not one grown by the bleed twice. A Full Document file keeps the +/// document's bleed around its art's bounds, which Include Bleed doesn't grow. +#[test] +fn include_bleed_native_files_hold_the_bleed_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("document.setup", &json!({"bleed": 9})).unwrap(); + let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]})); + let [(_, pdf)] = &files(&r)[..] else { panic!("one PDF: {r}") }; + let [(media, bleed, ..)] = page_sizes(pdf)[..] else { panic!("one page") }; + let reopened = |name: &str, bytes: &[u8]| -> (Session, Vec) { + let mut t = Session::new(); + t.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + let r = t.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}, "preserveEditing": false})).unwrap(); + let pages = page_sizes(&b64(&r)); + (t, pages) + }; + for format in ["vectorcraft", "ai", "eps"] { + let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": format}]})); + let [(name, bytes)] = &files(&r)[..] else { panic!("one {format} file: {r}") }; + let (t, pages) = reopened(name, bytes); + let [(m, b, trim, _)] = pages[..] else { panic!("{format}: one page") }; + assert_eq!((m, b), (media, bleed), "{format}: the page of the PDF row"); + assert_eq!(trim, bleed, "{format}: the artboard holds the bleed"); + assert_eq!(t.doc().unwrap().doc.setup.bleed, [0.0; 4], "{format}: no second bleed"); + } + // Full Document: the art's bounds, with the document's bleed around them. + let r = export(&mut s, json!({"includeBleed": true, "fullDocument": true, "formats": [{"format": "vectorcraft"}]})); + let [(name, bytes)] = &files(&r)[..] else { panic!("one file: {r}") }; + let (t, _) = reopened(name, bytes); + assert_eq!(t.doc().unwrap().doc.setup.bleed, [9.0; 4]); +} diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 7b5545ddca..2790a1350c 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -115,6 +115,10 @@ fn junk_options_are_rejected() { json!({"svg": "css"}), json!({"images": "inline"}), json!({"useArtboards": "yes"}), + json!({"units": "furlong"}), + json!({"units": 7}), + json!({"units": null}), + json!({"svg": {"units": null}}), ] { let mut q = p.clone(); q["format"] = json!("svg"); @@ -124,6 +128,39 @@ fn junk_options_are_rejected() { assert!(s.execute("document.export", &json!({"format": "png", "styling": "fancy"})).is_ok()); } +/// #4462: width and height carry the chosen unit (the document is 200 × 100 pt, the viewBox stays +/// in points), px is today's bare numbers, and Responsive leaves the size out whatever the unit. +#[test] +fn svg_export_writes_width_height_with_the_requested_unit() { + let mut s = session(1); + let plain = svg(&mut s, json!({})); + assert!(plain.contains(" width=\"200\" height=\"100\" viewBox=\"0 0 200 100\""), "{plain}"); + assert_eq!(svg(&mut s, json!({"units": "px"})), plain, "px keeps bare point coordinates"); + for unit in ["mm", "cm", "in", "pt"] { + for decimals in [1, 3] { + for p in [json!({"units": unit, "decimals": decimals}), json!({"svg": {"units": unit, "decimals": decimals}})] { + let out = svg(&mut s, p); + assert!(out.contains(&format!("{unit}\"")) && out.contains("viewBox=\"0 0 200 100\""), "{unit}:\n{out}"); + let back = vectorcraft_svg::import(&out).unwrap(); + let rect = back.artboards[0].rect; + assert!((rect.width() - 200.0).abs() < 0.001 && (rect.height() - 100.0).abs() < 0.001, "{unit}: {rect:?}\n{out}"); + } + } + } + let out = svg(&mut s, json!({"units": "mm", "responsive": true})); + assert!(!out.contains("mm\"") && !out.contains("height=\"100\" viewBox") && out.contains("viewBox=\"0 0 200 100\""), "{out}"); + assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("x=\"10.1\""), "coordinate precision is unchanged"); + // Omitted units retain main's document-unit save behavior, including serialized defaults. + s.execute("document.setUnits", &json!({"units": "millimeters"})).unwrap(); + let defaults = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap(); + assert!(svg(&mut s, json!({"svg": defaults})).contains("mm\"")); + for p in [json!({"units": "px"}), json!({"svg": {"units": "px"}})] { + assert_eq!(svg(&mut s, p), plain, "explicit pixels override physical document units"); + } + assert_eq!(svg(&mut s, json!({"units": "mm", "svg": {"units": "px"}})), plain, "nested units override flat units"); + assert_eq!(svg(&mut s, json!({"units": null, "svg": {"units": "px"}})), plain, "nested units override flat null"); +} + #[test] fn several_artboards_write_one_file_each() { let mut s = session(3); diff --git a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs index f36fa14b8d..74df5216aa 100644 --- a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs +++ b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs @@ -104,8 +104,15 @@ fn bmp_options_reach_the_file() { assert_eq!(i32::from_le_bytes(flipped[22..26].try_into().unwrap()), -40, "top-down rows"); let os2 = bmp(&mut s, json!({"fileFormat": "os2", "depth": 4})); assert_eq!(u32::from_le_bytes(os2[14..18].try_into().unwrap()), 12, "OS/2 core header"); - let gray = image::load_from_memory_with_format(&bmp(&mut s, json!({"colorModel": "gray", "depth": 8})), image::ImageFormat::Bmp).unwrap(); - assert!(gray.to_rgb8().pixels().all(|p| p[0] == p[1] && p[1] == p[2])); + // A red square, whose gray is neither black nor white. + let red = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 40})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [red], "color": "#ff0000"})).unwrap(); + let gray = + image::load_from_memory_with_format(&bmp(&mut s, json!({"colorModel": "gray", "depth": 8})), image::ImageFormat::Bmp).unwrap().to_rgb8(); + assert_eq!(gray.dimensions(), (60, 40)); + assert!(gray.pixels().all(|p| p[0] == p[1] && p[1] == p[2])); + let [r, _, _] = gray.get_pixel(5, 20).0; + assert!(r > 0 && r < 255, "red is a middle gray: {r}"); for bad in [ json!({"depth": 2}), json!({"depth": 24, "rle": true}), diff --git a/crates/engine/src/cmd/findfiles/tests.rs b/crates/engine/src/cmd/findfiles/tests.rs index 9340e5a8c6..65a7d12edf 100644 --- a/crates/engine/src/cmd/findfiles/tests.rs +++ b/crates/engine/src/cmd/findfiles/tests.rs @@ -30,19 +30,29 @@ impl Visitor for Names { } } -/// Reads every file, and waits on reading one until its channel sends or closes. -struct Blocked(Mutex>); +/// Reads every file, says on its second channel that a read began, and waits on reading one until +/// its first channel sends or closes. +struct Blocked(Mutex>, mpsc::Sender<()>); impl Visitor for Blocked { fn wants(&self, _: &str) -> bool { true } fn items(&self, _: &Path) -> Vec { + let _ = self.1.send(()); let _ = self.0.lock().unwrap().recv(); vec![] } } +/// A [`Blocked`] visitor with the sender that lets its reads end and the receiver that hears each +/// read begin. +fn blocked() -> (mpsc::Sender<()>, mpsc::Receiver<()>, Arc) { + let (go, wait_for_go) = mpsc::channel(); + let (entered, reading) = mpsc::channel(); + (go, reading, Arc::new(Blocked(Mutex::new(wait_for_go), entered))) +} + /// A test's folder tree, removed with everything in it when dropped, also when the test panics, /// and also when the test locked a folder in it. A removal that fails (a walker still holding a /// file open) is ignored. @@ -316,29 +326,35 @@ fn the_search_ends_at_its_limits_and_when_stopped() { #[test] fn the_search_answers_at_its_deadline_while_a_walker_is_blocked() { let root = tree("blocked", &["f.ttf"]); - let (tx, rx) = mpsc::channel(); + let (tx, reading, visitor) = blocked(); let started = Instant::now(); - let s = begin(root.clone(), rules(&root), Limits { seconds: 0.2, ..Limits::default() }, 1, 1, Arc::new(Blocked(Mutex::new(rx)))); - std::thread::sleep(Duration::from_millis(300)); + let s = begin(root.clone(), rules(&root), Limits::default(), 1, 1, visitor); + // The walker is blocked reading the file. + assert!(reading.recv_timeout(WAIT).is_ok(), "the walker reads the file"); + assert_eq!((s.progress().state(), s.progress().read), ("searching", 1)); + s.expire(); let p = s.progress(); // The search ended when it answered, and it ran no longer than the test has waited. let waited = started.elapsed().as_secs_f64(); assert_eq!((p.state(), p.stopped()), ("stopped", Some("time")), "{p:?}"); - assert!(p.seconds >= 0.2 && p.seconds <= waited, "{p:?}, {waited} s"); - let (tx2, rx2) = mpsc::channel(); - let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx2)))); - let until = Instant::now() + WAIT; - while s2.progress().read == 0 && Instant::now() < until { - std::thread::sleep(Duration::from_millis(2)); - } + assert!(p.seconds <= waited, "{p:?}, {waited} s"); + assert_eq!(s.progress().seconds, p.seconds, "the time it ended at stays"); + // A limit of no seconds has run out as the search starts; a long one hasn't. + let (_tx0, _, visitor) = blocked(); + let none = begin(root.clone(), rules(&root), Limits { seconds: 0.0, ..Limits::default() }, 1, 1, visitor); + assert_eq!(none.progress().stopped(), Some("time")); + let (tx2, reading2, visitor) = blocked(); + let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, visitor); + assert!(reading2.recv_timeout(WAIT).is_ok(), "the walker reads the file"); assert_eq!(s2.progress().state(), "searching"); s2.stop(); assert_eq!(s2.progress().stopped(), Some("stop")); drop((tx, tx2)); } -/// Every file is item 0; reading the second file waits until the channel closes. -struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>); +/// Every file is item 0; reading the second file says so on the second channel, then waits until +/// the first channel closes. +struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>, mpsc::Sender<()>); impl Visitor for SecondBlocks { fn wants(&self, _: &str) -> bool { @@ -348,6 +364,7 @@ impl Visitor for SecondBlocks { let mut read = self.0.lock().unwrap(); read.0 += 1; if read.0 == 2 { + let _ = self.1.send(()); let _ = read.1.recv(); } vec![0] @@ -360,11 +377,9 @@ impl Visitor for SecondBlocks { fn files_found_are_kept_as_they_are_read() { let root = tree("kept", &["a.ttf", "b.ttf", "c.ttf"]); let (tx, rx) = mpsc::channel(); - let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx))))); - let until = Instant::now() + WAIT; - while s.progress().read < 2 && Instant::now() < until { - std::thread::sleep(Duration::from_millis(2)); - } + let (second, reading_second) = mpsc::channel(); + let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx)), second))); + assert!(reading_second.recv_timeout(WAIT).is_ok(), "the walker reads a second file"); let p = s.progress(); assert_eq!((p.state(), p.hits.len()), ("searching", 1), "{p:?}"); s.stop(); @@ -527,16 +542,12 @@ fn system_roots_and_homes_are_told_by_what_they_hold() { fn a_search_starts_with_the_threads_left_and_fails_when_none_is() { static POOL: Pool = Pool::new(3); let root = tree("pool", &["f.ttf"]); - let blocked = || { - let (tx, rx) = mpsc::channel(); - (tx, Arc::new(Blocked(Mutex::new(rx))) as Arc) - }; - let (tx_a, a) = blocked(); - let (tx_b, b) = blocked(); + let (tx_a, _, a) = blocked(); + let (tx_b, _, b) = blocked(); let a = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 2, 1, a).unwrap(); let b = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 4, 1, b).unwrap(); assert_eq!(POOL.live(), 3); - let (_, c) = blocked(); + let (_, _, c) = blocked(); let c = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 1, 1, c); assert_eq!(c.err().as_deref(), Some("the search couldn't start: try again in a moment")); drop((tx_a, tx_b)); diff --git a/crates/engine/src/cmd/findfiles/walk.rs b/crates/engine/src/cmd/findfiles/walk.rs index ae05a04838..1512bd76c5 100644 --- a/crates/engine/src/cmd/findfiles/walk.rs +++ b/crates/engine/src/cmd/findfiles/walk.rs @@ -238,12 +238,18 @@ impl Search { self.shared.finish(&mut w, End::Stopped); } + /// Move the search's deadline to now, as if its time had run out. + #[cfg(test)] + pub(crate) fn expire(&self) { + self.shared.deadline.store(0, Ordering::Relaxed); + } + /// Where the search stands. Past its deadline it has ended ([`End::Time`]), even while a walker /// is still waiting for a slow folder or file. pub fn progress(&self) -> Progress { let s = &self.shared; let mut w = s.lock(); - if w.end.is_none() && Instant::now() >= s.deadline { + if w.end.is_none() && s.time_up() { s.finish(&mut w, End::Time); } Progress { @@ -310,7 +316,7 @@ pub(crate) fn start_in( entries: AtomicU64::new(0), read: AtomicU64::new(0), started, - deadline: started + Duration::from_secs_f64(seconds), + deadline: AtomicU64::new(u64::try_from(Duration::from_secs_f64(seconds).as_nanos()).unwrap_or(u64::MAX)), limits, items, given: rules, @@ -355,7 +361,8 @@ struct Shared { entries: AtomicU64, read: AtomicU64, started: Instant, - deadline: Instant, + /// Nanoseconds after `started` at which the search's time is up. + deadline: AtomicU64, limits: Limits, items: usize, /// The rules given to [`start`], else this computer's, read by the first walker. @@ -419,7 +426,12 @@ impl Shared { /// Whether to stop listing and reading: the search ended or its time is up. fn should_stop(&self) -> bool { - self.stop.load(Ordering::Relaxed) || Instant::now() >= self.deadline + self.stop.load(Ordering::Relaxed) || self.time_up() + } + + /// Whether the search's time is up: [`Shared::deadline`] nanoseconds passed since it started. + fn time_up(&self) -> bool { + u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX) >= self.deadline.load(Ordering::Relaxed) } /// Whether the folders waiting to be listed and `more` folders found in the folder being listed @@ -618,7 +630,7 @@ fn walker(s: &Shared) { if w.end.is_some() { return; } - if Instant::now() >= s.deadline { + if s.time_up() { s.finish(&mut w, End::Time); return; } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 06fb062e50..f348a97f3c 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -54,8 +54,8 @@ pub(crate) use series::{ capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art, - is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, - series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, + is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, + series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 6c87143618..ad7f145af0 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -328,7 +328,9 @@ pub(super) fn column_art( } parts.push(Arc::new(d.reid(&crate::cmd::place::transformed(n, by)))); } - Some(Arc::new(Node::group(d.alloc_id(), parts))) + let mut n = Node::group(d.alloc_id(), parts); + n.extras_mut().graph_design_art = true; + Some(Arc::new(n)) }; let mut parts = vec![]; let (mut label, mut sliding) = (fit_affine(frame, rect), None); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index b5d5632356..b5faf1ccf8 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -271,7 +271,9 @@ impl Gen<'_> { /// A copy of design art drawn in a series: a single path gets a group of its own, as painting a series paints the /// paths directly inside its group and the design keeps its own paint. fn design_copy(&mut self, n: Arc) -> Arc { - if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n } + let mut n = if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n }; + Arc::make_mut(&mut n).extras_mut().graph_design_art = true; + n } /// A series group. Empty series are omitted by the caller; the index is stored on the group /// so later paint edits find the series without counting siblings. diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 3ea811392d..7371961c20 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -204,7 +204,7 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i /// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]). /// It is looked up through its parent, with no pass over the document: the panels call this while they draw. -fn is_series_group(doc: &Document, n: &Node) -> bool { +pub(crate) fn is_series_group(doc: &Document, n: &Node) -> bool { let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref()); graph.is_some_and(|spec| index < series_count(spec)) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5ac5a3bb51..b41415ef02 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -2588,6 +2588,7 @@ fn a_line_series_draws_its_kept_stroke_on_the_line_and_its_kept_fill_on_the_mark s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); let (drawn, others) = line_parts(&s, id); assert_eq!((drawn.appearance.fill_paint(), drawn.appearance.stroke_paint()), (Paint::None, red)); + assert!(!others.is_empty(), "the markers and the legend swatch are drawn"); assert!(others.iter().all(|m| m.appearance.fill_paint() == blue), "{others:?}"); } @@ -4867,7 +4868,7 @@ fn blanks_read_back_as_null_and_year_header_rows_still_read_as_headers() { #[test] fn a_huge_ragged_grid_is_capped() { let g = GraphSpec { rows: vec![vec![0.0; vectorcraft_doc::MAX_GRAPH_SERIES + 10]; 3], ..GraphSpec::default() }; - assert!(g.cells().iter().all(|r| r.len() == vectorcraft_doc::MAX_GRAPH_SERIES)); + assert_eq!(g.cells().iter().map(Vec::len).collect::>(), [vectorcraft_doc::MAX_GRAPH_SERIES; 3]); } #[test] @@ -6720,7 +6721,17 @@ fn designs_and_markers_survive_save_and_open() { d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Dot".into(), art: std::sync::Arc::new(dot) }); let art = super::generate(&mut d, &g); let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap(); - assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + let marks = s0.children().unwrap(); + assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(marks.iter().filter(|n| sized(n, 5.0)).count(), 1, "a default square at the one data point"); +} + +/// Whether `n` is a square path `side` points across, drawn as the four corners of its bounds (a default point marker +/// is 5, a default legend swatch 8). +fn sized(n: &vectorcraft_doc::Node, side: f64) -> bool { + let Some(b) = n.geometric_bounds() else { return false }; + let square = matches!(&n.kind, NodeKind::Path { path, .. } if *path == vectorcraft_geom::shapes::rectangle(b)); + square && (b.width() - side).abs() < 1e-6 && (b.height() - side).abs() < 1e-6 } #[test] @@ -6773,7 +6784,11 @@ fn designs_too_big_for_a_graph_are_refused_and_drawn_as_squares() { let mut d = (*s.doc().unwrap().doc).clone(); let art = super::generate(&mut d, &g); let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap(); - assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + let marks = s0.children().unwrap(); + assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(marks.iter().filter(|n| sized(n, 5.0)).count(), 200, "a default square at each of the 200 points"); + let line = marks.iter().filter(|n| n.geometric_bounds().is_some_and(|b| b.width() > 100.0)).count(); + assert_eq!(line, 1, "the series line is drawn as well"); // Too many objects for one design. let ids: Vec = (0..2001) .map(|i| s.execute("shape.rectangle", &json!({"x": i % 40, "y": i / 40, "width": 1, "height": 1})).unwrap()["id"].as_u64().unwrap()) @@ -7157,7 +7172,16 @@ fn graph_column_params_are_checked_and_designs_too_big_are_drawn_plain() { let mut d = (*s.doc().unwrap().doc).clone(); let art = super::generate(&mut d, &g); let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap(); - assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + let marks = s0.children().unwrap(); + assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(marks.iter().filter(|n| sized(n, 8.0)).count(), 1, "a default square as the legend swatch"); + let columns: Vec<_> = marks.iter().filter(|n| !sized(n, 8.0)).collect(); + assert_eq!(columns.len(), 1, "one plain column for the one value"); + let bounds = columns[0].geometric_bounds(); + let height = bounds.map(|b| b.height()); + assert!(height.is_some_and(|h| (h - 140.0).abs() < 1e-6), "the column has the value's height: {height:?}"); + let rectangle = bounds.map(vectorcraft_geom::shapes::rectangle); + assert!(matches!(&columns[0].kind, NodeKind::Path { path, .. } if Some(path) == rectangle.as_ref()), "the plain column is a rectangle"); // Columns of 0 on a value axis from 10,000 to 10,001 run 2,000,000 points from the clamped zero line: a copy each // 0.1 is past the budget too. let far = one_series(&mut s, "column", &[0.0, 0.0]); @@ -7840,7 +7864,9 @@ fn the_legend_across_top_keeps_above_labels_over_the_plot() { let n = s.doc().unwrap().doc.node(col).unwrap().clone(); let texts: Vec<_> = group(&n, "Legend").children().unwrap().iter().filter_map(|c| c.geometric_bounds()).collect(); let last_row = texts.iter().map(|b| b.y0).fold(f64::MIN, f64::max); - assert!(texts.iter().filter(|b| b.y0 < last_row - 1e-6).all(|b| b.x1 <= 400.0 + 1e-6), "{texts:?}"); + let above: Vec<_> = texts.iter().filter(|b| b.y0 < last_row - 1e-6).collect(); + assert!(!above.is_empty(), "the legend takes more than one row: {texts:?}"); + assert!(above.iter().all(|b| b.x1 <= 400.0 + 1e-6), "{texts:?}"); } #[test] @@ -8024,6 +8050,7 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() { s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); s.execute("text.setStyle", &json!({"size": 12})).unwrap(); let looks = label_looks(&mut s, id); + assert!(!looks.is_empty()); assert!(looks.iter().all(|(_, size, _)| (*size - 12.0).abs() < 1e-6), "{looks:?}"); let g = spec(&s, id); assert!(g.label_styles.values.is_some() && g.label_styles.categories.is_some() && g.label_styles.legend.is_some()); @@ -9145,10 +9172,13 @@ fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) { (stroke, n.appearance.stroke_width(), n.opacity) } -/// The looks of graph `id`'s lines after it is drawn again. +/// The looks of graph `id`'s lines after it is drawn again: more than three (a radar graph's +/// three spokes come first, then its rings). fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> { s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); - line_nodes(s, id).iter().map(line_look).collect() + let looks: Vec<_> = line_nodes(s, id).iter().map(line_look).collect(); + assert!(looks.len() > 3, "the graph is drawn with its lines: {looks:?}"); + looks } /// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index b54e92932c..9677f23ad6 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -28,7 +28,9 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; let shape = match text_param(p, "shape", C)? { - Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, + Some(v) => { + DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? + } None => DotShape::Circle, }; let frequency = number_or(p, "frequency", 20.0, C)?; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 65f268f2b0..142cb8a654 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Placement Options", [], None, - "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}", + "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}", has_doc, placement_options ), @@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default(); drop(doc); if preserve.is_none() && align.is_none() && clip.is_none() { - return Ok(json!({ "placement": placement_json(first) })); + return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) })); } let set = |o: &mut PlacementOptions| { o.preserve = preserve.unwrap_or(o.preserve); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 21f3661c89..7f54f8c03f 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "New Document Profiles", [], None, - "{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}", + "{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), unusable?: why file.new does not read it (a link or a folder: new documents get the defaults, and file.newProfiles.edit refuses it), path?; customized, unusable and path left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}", always, list_profiles ), @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Edit Profile", [], None, - "{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", + "{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; an error when its file is a link or a folder, which file.new does not read either; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", always, edit_profile ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Reset Profile", [], None, - "{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", + "{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again (a link is removed, not the file it leads to; a folder is not deleted, an error); an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", always, reset_profile ), @@ -299,7 +299,11 @@ impl DocSettings { } /// These settings with `p`'s changes (the params of `file.new`) → validated. - pub fn with_params(mut self, p: &Value, cmd: &str) -> Result { + pub fn with_params(self, p: &Value, cmd: &str) -> Result { + self.with_params_inner(p, cmd, false) + } + + fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result { if let Some(u) = p.get("units").filter(|v| !v.is_null()) { let u = u.as_str().unwrap_or(""); self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?; @@ -329,11 +333,11 @@ impl DocSettings { Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))), } if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) { - let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?; - self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32; + self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) } + .ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?; } if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) { - self.layout_params(l, cmd)?; + self.layout_params(l, cmd, replaying)?; } if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) { self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?; @@ -371,7 +375,7 @@ impl DocSettings { } /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. - fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { + fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; @@ -380,25 +384,22 @@ impl DocSettings { } return Ok(()); } - let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?; for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 + self.columns = + if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } + .ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "rows" => { - self.rows = v - .as_f64() - .map(f64::round) - .filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r)) - .map(|r| r as u32) - .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))? + self.rows = if replaying { + v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + } else { + count(v) + } + .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "spacing" => { self.spacing = v @@ -407,7 +408,7 @@ impl DocSettings { .ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))? } "rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?, - _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), + _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))), } } if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { @@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result Option { + v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) @@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut settings = base.with_params_inner(p, C, s.replaying())?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } @@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, None => s.default_settings(), }; - let mut preset = base.with_params(p, C)?; + let mut preset = base.with_params_inner(p, C, s.replaying())?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) { @@ -996,6 +1003,44 @@ pub fn profile_names() -> impl Iterator { CATEGORIES.iter().map(|c| c.0) } +/// What is at a New Document profile's file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileFile { + /// Nothing: the shipped profile applies. + None, + /// A plain file, which `file.new` reads. + Plain, + /// A link or another entry that is not a plain file or a folder: `file.new` does not read it (the + /// new document has the defaults), `file.newProfiles.edit` does not open it and + /// `file.newProfiles.reset` removes it (a link, not what it leads to). + NotPlain, + /// A folder, which `file.new` does not read and `file.newProfiles.edit` does not open either. + /// `file.newProfiles.reset` does not delete a folder. + Folder, +} + +impl ProfileFile { + /// Whether the category has a file in place of the shipped profile. + pub fn customized(self) -> bool { + self != Self::None + } + + /// Whether `file.newProfiles.reset` removes what is there. + pub fn resettable(self) -> bool { + matches!(self, Self::Plain | Self::NotPlain) + } +} + +/// What is at `path`, looked at without following a link. +fn profile_file(path: &std::path::Path) -> ProfileFile { + match std::fs::symlink_metadata(path) { + Ok(m) if crate::store::is_plain(&m) => ProfileFile::Plain, + Ok(m) if m.is_dir() && !crate::store::is_link_entry(&m) => ProfileFile::Folder, + Ok(_) => ProfileFile::NotPlain, + Err(_) => ProfileFile::None, + } +} + /// The profile `v` names (a built-in category, any case). fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> { let name = v.as_str().map(str::trim).unwrap_or_default(); @@ -1022,9 +1067,9 @@ impl Session { Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION))) } - /// Whether profile `name` has a file, which `file.newProfiles.reset` deletes. - pub fn new_doc_profile_customized(&self, name: &str) -> bool { - self.profile_path(name).is_some_and(|p| p.is_file()) + /// What is at profile `name`'s file, looked at without following a link. + pub fn new_doc_profile_file(&self, name: &str) -> ProfileFile { + self.profile_path(name).map_or(ProfileFile::None, |p| profile_file(&p)) } /// Profile `name`'s document, its file's path and a warning for each color profile the file @@ -1045,11 +1090,13 @@ impl Session { match std::fs::symlink_metadata(&path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), // A link is refused: the script's gate does not check where it leads. - Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + Ok(m) if !crate::store::is_plain(&m) => return Err(crate::store::NOT_PLAIN.to_string()), _ => {} } crate::file_access::check_read(&file).map_err(denied)?; - crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + // Read without following a link, so a link put in the file's place since the check + // above is refused too. + crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some) })?; let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs @@ -1086,7 +1133,11 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result { // A request that may not read the folder learns nothing of its files. Some(path) => { if let Some(p) = shown(&path) { - v["customized"] = json!(path.is_file()); + let file = profile_file(&path); + v["customized"] = json!(file.customized()); + if matches!(file, ProfileFile::NotPlain | ProfileFile::Folder) { + v["unusable"] = json!(crate::store::NOT_PLAIN); + } v["path"] = json!(p); } } @@ -1119,12 +1170,19 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result { let path = file.to_string_lossy().to_string(); // document.open reads it next: a profile it can't open is not written either. crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?; - if !file.exists() { - let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); - file.parent() - .map_or(Ok(()), std::fs::create_dir_all) - .and_then(|()| std::fs::write(&file, bytes)) - .map_err(|e| profile_error(format!("{path}: {e}"), &path))?; + match profile_file(&file) { + ProfileFile::Plain => {} + // file.new does not read a link or a folder, so it is not opened as the profile either. + ProfileFile::NotPlain | ProfileFile::Folder => return Err(profile_error(format!("{path}: {}", crate::store::NOT_PLAIN), &path)), + // Made new, so a dangling link put there since is not written through. + ProfileFile::None => { + let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); + file.parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::OpenOptions::new().write(true).create_new(true).open(&file)) + .and_then(|mut f| std::io::Write::write_all(&mut f, &bytes)) + .map_err(|e| profile_error(format!("{path}: {e}"), &path))?; + } } s.execute("document.open", &json!({ "path": path })) } @@ -1134,9 +1192,14 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result { let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; let file = writable_profile(s, name, C)?; let path = file.to_string_lossy().to_string(); + if profile_file(&file) == ProfileFile::Folder { + return Err(profile_error(format!("{path}: a folder, which Reset does not delete"), &path)); + } let reset = match std::fs::remove_file(&file) { Ok(()) => true, Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + // On Windows a link to a folder, or a junction, is removed as a folder; what it leads to stays. + Err(_) if std::fs::symlink_metadata(&file).is_ok_and(|m| crate::store::is_link_entry(&m)) && std::fs::remove_dir(&file).is_ok() => true, Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)), }; Ok(json!({ "name": name, "reset": reset })) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index b2d857a464..2c875762a6 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -41,5 +41,5 @@ pub(crate) use pixelgrid::{ snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; -pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index de893c79da..3b949efd8b 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 7bef1cbc69..5b0d47baa2 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) { } } +/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound +/// path is read at the parent's place, without looking either object up by id. +pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) { + let Some((_, up)) = path.split_last() else { return }; + if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) { + return; + } + if let Some(n) = d.node_mut_at(up) { + snap_object(n, sc); + } +} + /// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added /// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity /// mask, to the pixel grid. Objects the edit did not touch are not visited. diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index c86bd4c792..72cc39e5c7 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -66,10 +66,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling { /// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of /// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then. pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { + let paths = s.doc()?.doc.index_paths(ids.iter().copied()); + transform_patterns_at(s, p, ids, &paths) +} + +/// [`transform_patterns`] with `paths`, the places of `ids` in the document's tree, found already. +fn transform_patterns_at(s: &mut Session, p: &Value, ids: &[NodeId], paths: &std::collections::HashMap>) -> Result { let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles); let d = &s.doc()?.doc; let mut uses = false; - let paths = d.index_paths(ids.iter().copied()); for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) { uses |= uses_pattern_with_masks(n); } @@ -152,7 +157,9 @@ fn apply_transform_moving_guides( let areas = bool_or(p, "typeAreas", false); let objects = transforms_objects(p); let mut sc = if Scaling::factor(xf).is_some() { scaling(s, p) } else { Scaling::default() }; - sc.patterns = transform_patterns(s, p, &ids)?; + // The places of `ids`, found in one walk for Transform Patterns and for the edit below. + let paths = s.doc()?.doc.index_paths(ids.iter().copied()); + sc.patterns = transform_patterns_at(s, p, &ids, &paths)?; let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = guides.unwrap_or(Vec2::new(c[4], c[5])); @@ -174,8 +181,6 @@ fn apply_transform_moving_guides( // An edit normally preserves the tree positions already found here. Settling an active // typing session can change the document before the edit closure runs, so look up again then. let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s)); - let d = &s.doc()?.doc; - let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). let mut interpolate = None; @@ -195,7 +200,7 @@ fn apply_transform_moving_guides( // A move of whole objects, not of copies (which `reindex` covers): the document before it, // and the moved objects as the transform left them, for [`moved_by`] to check after the edit. let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?; - let mut held: Vec<(NodeId, Arc)> = vec![]; + let mut held: Vec<(Vec, Arc)> = vec![]; let targets = s.edit(label, |d, sel| { let mut targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the @@ -235,11 +240,12 @@ fn apply_transform_moving_guides( } // Holding them makes any later change to them copy them first, which `moved_by` sees. if from.is_some() { - held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect(); + held = targets.iter().filter_map(|id| paths.get(id)).filter_map(|p| Some((p.clone(), node_arc(d, p)?))).collect(); } if objects { - for id in &targets { - super::pixelgrid::keep_compound_aligned(d, *id, sc); + // The transforms above leave every object at its place, so `paths` still holds them. + for p in targets.iter().filter_map(|id| paths.get(id)) { + super::pixelgrid::keep_compound_aligned_at(d, p, sc); } // Moving all of the tile art moves the tile as far. if let Some(before) = tile_art { @@ -288,20 +294,22 @@ fn node_arc(d: &Document, path: &[usize]) -> Option> { } /// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved -/// objects as the transform left them (`held`). `None` unless every moved object is still that -/// node, none is a member of a blend (whose spine follows its members), and every object the -/// selection shows, the key object and the key anchor's object included, is a moved object or -/// inside one. A pass after the transform that changes a moved object, such as the one that snaps -/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it -/// first, so it is no longer that node. -fn moved_by(from: &Arc, st: &crate::DocState, held: &[(NodeId, Arc)], by: Vec2) -> Option { +/// objects as the transform left them (`held`, each with its index path). `None` unless every moved +/// object is still that node at its path, none is a member of a blend (whose spine follows its +/// members), and every object the selection shows, the key object and the key anchor's object +/// included, is a moved object or inside one. A pass after the transform that changes a moved +/// object, such as the one that snaps moved pixel-aligned objects to the pixel grid again +/// ([`super::pixelgrid::refresh`]), copies it first, so it is no longer that node. The checks read +/// the nodes at their paths and look nothing up by id. +fn moved_by(from: &Arc, st: &crate::DocState, held: &[(Vec, Arc)], by: Vec2) -> Option { let d = &st.doc; - let unchanged = |(id, n): &(NodeId, Arc)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n))); + let unchanged = |(p, n): &(Vec, Arc)| d.node_at(p).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n))); if held.is_empty() || !held.iter().all(unchanged) { return None; } - let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. })); - if held.iter().any(|(id, _)| in_blend(*id)) { + // The node at each path is the moved object, so its parent is the node one level up. + let in_blend = |p: &[usize]| p.split_last().and_then(|(_, up)| d.node_at(up)).is_some_and(|parent| matches!(parent.kind, NodeKind::Blend { .. })); + if held.iter().any(|(p, _)| in_blend(p)) { return None; } let mut moved = std::collections::HashSet::new(); @@ -430,11 +438,16 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { (v.x, v.y) } +pub(crate) use vectorcraft_tools::nudge_step; + +/// `object.nudge`, the arrow keys: the selected anchors, else the selected objects (and the guides +/// that move with them), else the selected ruler guides move by [`nudge_step`] in the arrow's +/// direction, in one undo step. pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big", "interpolate"], "object.nudge")?; - let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; + check_switches(p, &["big", "fine", "interpolate"], "object.nudge")?; + let k = nudge_step(s.prefs.keyboard_increment, bool_or(p, "big", false), bool_or(p, "fine", false)); let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. let (gx, gy) = (dx, dy); diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index a64d038d8f..bc07e7ccb5 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -185,14 +185,27 @@ fn can_change_mask(s: &Session) -> std::result::Result<(), String> { /// most one outermost object, which it masks with `ids` (a call's `ids` stand in for the selection /// here). A targeted layer is one subject root however many objects it selects. `make` itself /// refuses any single target in those modes, a layer included, so a selection with a target counts -/// as one object. +/// as one object. The check sorts the selection into paint order for its outermost objects only when it has one +/// subject root and no target. fn can_make(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; let Some(st) = s.active() else { return Ok(()) }; let roots = super::appearance::subject_roots(s).map_or(0, |r| r.len()); - let outermost = super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len(); - let targeted = st.selection.target.is_some(); - if roots == 1 && (outermost <= 1 || targeted) { super::maskedit::can_edit_mask(s) } else { Ok(()) } + if roots != 1 { + return Ok(()); + } + let one = st.selection.target.is_some() || { + #[cfg(test)] + OUTERMOST_FOUND.set(OUTERMOST_FOUND.get() + 1); + super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len() <= 1 + }; + if one { super::maskedit::can_edit_mask(s) } else { Ok(()) } +} + +#[cfg(test)] +thread_local! { + /// How many times [`can_make`] found the selection's outermost objects on this thread. + static OUTERMOST_FOUND: std::cell::Cell = const { std::cell::Cell::new(0) }; } fn make(s: &mut Session, p: &Value) -> Result { @@ -485,6 +498,12 @@ impl Session { _ => TransparencyInfo::default(), } } + + /// The first of the objects the Transparency panel shows ([`TransparencyInfo::ids`]), without comparing their + /// values. + pub fn transparency_target(&self) -> Option { + transparency_targets(self, &Value::Null).ok()?.first().copied() + } } fn info(s: &mut Session, p: &Value) -> Result { @@ -759,4 +778,22 @@ mod tests { let back = vectorcraft_format::load(&bytes).unwrap(); assert_eq!(back.node(NodeId(a)).unwrap().extras().mask, d.node(NodeId(a)).unwrap().extras().mask); } + + /// Make Opacity Mask's check sorts the selection for its outermost objects only when the selection has one + /// subject root; with several roots it is enabled without that sort. + #[test] + fn the_make_check_sorts_only_a_selection_with_one_root() { + let (mut s, a, b) = session_with_two(); + let found = || OUTERMOST_FOUND.get(); + select(&mut s, &[a, b]); + let before = found(); + assert_eq!(can_make(&s), Ok(())); + assert_eq!(found(), before, "two roots: no paint-order sort"); + select(&mut s, &[a]); + assert_eq!(can_make(&s), Ok(())); + assert_eq!(found(), before + 1, "one root: the outermost objects are found"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(can_make(&s), Ok(())); + assert_eq!(found(), before + 1, "no roots: no sort"); + } } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..2a61f7fb74 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool { 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. + /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group, + /// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document. 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()) { return std::collections::HashSet::new(); } - live_paint_covered(&self.doc, ids) + self.live_paint_covered_kept(ids) } } diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index ec8f02f700..9b0fb393df 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() { assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); } +/// How many times this thread read the groups around selected objects for their Live Paint faces +/// and edges ([`DocState::live_paint_covered_kept`]). +fn cover_reads() -> usize { + crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get) +} + +/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel +/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the +/// objects' groups once for each version of the document and selection, not once for each question. +/// A Live Paint group selected with one of its faces still counts the face with its group. +#[test] +fn live_paint_faces_are_looked_for_once_per_document_version() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids: Vec = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record"); + let ask = |s: &Session| { + for _ in 0..3 { + s.proxy_paints(); + s.shown_stroke(); + s.proxy_mixed(); + s.active().unwrap().stroke_mixed(); + } + }; + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "one read for this version of the document"); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "an edit reads them again, once"); + s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "another selection reads them again, once"); + + // A Live Paint group with one of its edges selected too: the edge counts with its group on every ask. + s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap(); + let group = s.active().unwrap().selection.objects[0]; + let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id; + s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap(); + let st = s.active().unwrap(); + let covered = live_paint_covered(&st.doc, &st.selection.objects); + assert!(covered.contains(&edge)); + for _ in 0..2 { + assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered); + } +} + /// Random selections of a document with nested groups answer as a walk does. #[test] fn random_selections_match_a_walk_of_the_document() { diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index dcc3eade04..7c1a46350d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -43,7 +43,7 @@ use std::sync::OnceLock; use serde_json::Value; use vectorcraft_apischema::shown_key; -use super::{bad, command_specs, find_command}; +use super::{bad, color_is_finite, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. @@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), ("addon.pathtools.bridge", "radius", "gap"), + ("addon.pathtools.commonTangents", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; @@ -608,16 +609,16 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { /// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`, /// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers -/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its -/// default color for any other value, except that an array of three or more entries draws an -/// entry that isn't a number as 0. +/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`), with no component too +/// large to store ([`color_is_finite`])? The effect draws its default color for any other value, +/// except that an array of three or more entries draws an entry that isn't a number as 0. /// /// [`Color::from_hex`]: vectorcraft_color::Color::from_hex fn is_effect_color(v: &Value) -> bool { match v { Value::String(s) => vectorcraft_color::Color::from_hex(s).is_some(), - Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number), - Value::Object(_) => serde_json::from_value::(v.clone()).is_ok(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|n| n.as_f64().is_some_and(|n| (n as f32).is_finite())), + Value::Object(_) => serde_json::from_value::(v.clone()).is_ok_and(|c| color_is_finite(&c)), _ => false, } } @@ -956,11 +957,10 @@ fn option_trees() -> Value { let mut trees = pdf_option_tree(); if let Some(tree) = trees.as_object_mut() { tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default()); - let mut svg = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap_or_default(); - if let Some(svg) = svg.as_object_mut() { - svg.extend(super::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]).map(|k| (k.to_string(), Value::Null))); - } - tree.insert("svg".into(), svg); + // Serialized defaults omit optional overrides such as units; the registry lists every key. + let svg = super::fileio::FORMATS.iter().find(|f| f.id == "svg").into_iter().flat_map(|f| f.options); + let svg = svg.filter(|o| o.name != "svg").map(|o| (o.name.to_string(), Value::Null)).collect(); + tree.insert("svg".into(), Value::Object(svg)); } trees } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 61406fdc61..cacafa5d06 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Divide", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front). When open paths are among them, the command stops with an error and leaves the art unchanged if the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {ids}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Divide) ), @@ -823,7 +823,8 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { if shapes.iter().any(|s| s.path.subpaths.iter().any(|sp| sp.anchors.iter().any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())))) { return Err(EngineError::Other("paths contain invalid coordinates".into())); } - let mut results = po::pathfinder_with(op, &shapes, options.precision); + let mut results = po::try_pathfinder_with(op, &shapes, options.precision) + .map_err(|e| EngineError::Other(format!("{label}: {e} to cut with the open paths; select fewer paths")))?; if options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline) { // Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: the pieces // of objects with no fill (or only hidden ones) go. @@ -1562,6 +1563,12 @@ pub fn auto_simplify_level(s: &Session) -> Result { fn simplify(s: &mut Session, p: &Value) -> Result { const C: &str = "object.path.simplify"; let (auto, given_level, given_tolerance) = (switch_or(p, "auto", false, C)?, number_given(p, "level", C)?, length_given(p, "tolerance", C)?); + if given_tolerance.is_some_and(|t| t < 0.0) { + return Err(bad(C, "`tolerance` must be 0 or more")); + } + if given_level.is_some_and(|l| !(0.0..=100.0).contains(&l)) { + return Err(bad(C, "`level` must be from 0 to 100")); + } let corner_angle = number_given(p, "cornerAngle", C)?.unwrap_or(30.0).clamp(0.0, 180.0); let (straight_lines, whole) = (switch_or(p, "straightLines", false, C)?, switch_or(p, "wholePaths", false, C)?); // With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given. diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 7595cb0b86..27353207d1 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", + "addon.arrange.markBounds", "addon.arrange.match", "addon.arrange.offset", "addon.arrange.randomizeOpacity", @@ -30,6 +32,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.color.fillToStroke", "addon.color.filter", "addon.color.nearestSwatch", + "addon.color.randomFill", "addon.color.select", "addon.color.strokeToFill", "addon.color.swatchLegend", @@ -83,6 +86,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pen.segment", "addon.pen.togglePoint", "addon.select.byArtboards", + "addon.select.editPointsOnly", "addon.shapes.box3d", "addon.shapes.configure", "addon.shapes.ellipse", @@ -409,6 +413,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.stepAndRepeat", "object.tag.add", "object.tag.remove", "object.tag.removeAll", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 27d38e158f..8420e67d30 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -725,6 +725,8 @@ impl Session { for e in self.prefs.keep_folders(&mut p) { log::warn!("{e}"); } + // Tool settings saved by an earlier version are updated once. + p.migrate_tool_settings(); // Saved gradient presets get names no built-in preset or other saved one has. for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) { log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name"); diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 13086d1321..5d37ec4e9c 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -12,7 +12,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings}; use super::fileio::pdf::{merge, pdf_error}; use super::fileio::{extension, write_or_return}; use super::flatten::has_transparent_tile_images; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param, u64_req}; const SETUP: &str = "print.setup"; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Print", [], Some("Cmd+P"), - "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", + "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), maxPages?: n (a whole number: the job is composed only when it prints at most n pages, copies counted; with more, nothing is composed or written and the reply is {pages, format}), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", has_doc, print ), @@ -222,6 +222,11 @@ fn print(s: &mut Session, p: &Value) -> Result { super::fileio::check_not_lossy_overwrite(s.doc()?, path, p, PRINT)?; } let postscript = to_postscript(p)?; + let max_pages = match p.get("maxPages") { + None => None, + Some(_) => Some(u64_req(p, "maxPages", PRINT)?), + }; + let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m); let doc = &s.doc()?.doc; let mut set = preset_or_saved(PRINT, s, doc, p)?; if postscript { @@ -244,6 +249,27 @@ fn print(s: &mut Session, p: &Value) -> Result { && !bitmap && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); + let level = match p.get("level").filter(|v| postscript && !v.is_null()) { + Some(v) => { + let t = super::fileio::dxf::text(v); + Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))? + } + None => Level::default(), + }; + // A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it, + // once the options are checked, when its pages follow from the artboards alone (composite, no + // `skipBlank`, artboards not ignored); the pages are counted again on the prepared art. + super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + let by_artboards = !set.skip_blank + && !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore) + && set.output.mode == vectorcraft_pdf::OutputMode::Composite; + if max_pages.is_some() + && by_artboards + && let Ok(pv) = vectorcraft_pdf::preview(doc, &set) + && too_many(pv.pages) + { + return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + } // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -251,7 +277,12 @@ fn print(s: &mut Session, p: &Value) -> Result { let which = set.print_layers; if !postscript { let printed = prepared.as_ref().unwrap_or(doc); - let typed = type_warnings(&full, which, &areas(&vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?)); + let laid_out = vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?; + // `maxPages` is checked on the art as it prints, before the job is composed. + if too_many(laid_out.pages) { + return Ok(json!({ "pages": laid_out.pages, "format": "pdf" })); + } + let typed = type_warnings(&full, which, &areas(&laid_out)); let mut r = vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; @@ -260,13 +291,6 @@ fn print(s: &mut Session, p: &Value) -> Result { r.warnings.extend(r.setting_notes); return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings })); } - let level = match p.get("level").filter(|v| !v.is_null()) { - Some(v) => { - let t = super::fileio::dxf::text(v); - Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))? - } - None => Level::default(), - }; // What the job loses, then the notes on the options: a reply lists them in that order. let (mut warnings, mut setting_notes) = (vec![], vec![]); if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { @@ -283,6 +307,9 @@ fn print(s: &mut Session, p: &Value) -> Result { }; let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; + if too_many(plan.order.len()) { + return Ok(json!({ "pages": plan.order.len(), "format": "postscript" })); + } let pages: Vec = plan .sheets .iter() diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index d5f90d2411..f035ff55f5 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -149,17 +149,30 @@ pub(crate) fn clip_group(d: &mut Document, path: PathData, rule: FillRule, art: } /// Render `nodes` alone over transparency: (premultiplied pixels, width, height). -fn render(doc: &Document, nodes: Vec, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered { - let mut tmp = doc.clone(); +fn render(doc: &mut Document, nodes: Vec, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered { + struct RestoreLayers<'a> { + doc: &'a mut Document, + original: Vec>, + } + + impl Drop for RestoreLayers<'_> { + fn drop(&mut self) { + std::mem::swap(&mut self.doc.layers, &mut self.original); + } + } + let mut layer = Node::layer(NodeId(u64::MAX), "raster", vectorcraft_doc::LayerColor::Preset(0)); if let Some(ch) = layer.children_mut() { *ch = nodes.into_iter().map(Arc::new).collect(); } - tmp.layers = vec![Arc::new(layer)]; + // Keep the same resource tables, including images made by earlier effects, without + // copying them for each render. Restore the original layers even if rendering unwinds. + let original = std::mem::replace(&mut doc.layers, vec![Arc::new(layer)]); + let scoped = RestoreLayers { doc, original }; let mut r = vectorcraft_render::Renderer::new(); r.threads = 0; // Art Optimized is supersampled, as in exports: shapes meeting edge to edge leave no seam. - r.render_region_with(&tmp, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() }) + r.render_region_with(scoped.doc, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() }) } /// The note for pixels drawn since [`vectorcraft_render::decode_failures`] stood at `failed`, when diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b4ad26400b..a0ba6d243c 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> used.into_iter().map(|(_, u)| u).collect() } +#[cfg(test)] +thread_local! { + /// Tests: how many objects [`several_colors`] read on this thread. + static SEVERAL_COLORS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read +/// until a second color turns up. +fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> bool { + struct Seen<'a> { + first: Option, + several: bool, + patterns: Vec<&'a str>, + } + impl<'a> Seen<'a> { + fn read(&mut self, m: &'a Node) { + #[cfg(test)] + SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1)); + let (first, several) = (&mut self.first, &mut self.several); + paints( + m, + &mut |c, _, _, _| { + let k = ColorKey::of(c); + match first { + None => *first = Some(k), + Some(f) => *several |= *f != k, + } + }, + &mut self.patterns, + ); + } + fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet>) { + if self.several || only.is_some_and(|o| !o.contains(&n.id)) { + return; + } + self.read(n); + for c in n.children().into_iter().flatten() { + self.read_tree(c, only); + if self.several { + return; + } + } + } + } + let mut seen = Seen { first: None, several: false, patterns: vec![] }; + for n in ids.iter().filter_map(|id| d.node(*id)) { + seen.read_tree(n, only); + if seen.several { + return true; + } + } + let mut next = 0; + while !seen.several + && let Some(&name) = seen.patterns.get(next) + { + next += 1; + for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { + let _ = a.try_walk(&mut |m| { + seen.read(m); + if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) } + }); + if seen.several { + break; + } + } + } + seen.several +} + +impl Session { + /// Whether the objects `recolor.colors` reads without `ids` use more than one color: the + /// selection, or with nothing selected the objects Select All takes. False without a document. + pub fn several_colors_used(&self) -> bool { + let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false }; + self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref())) + } +} + /// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint /// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and /// add the patterns it is painted with to `patterns`. @@ -2050,6 +2128,69 @@ mod tests { assert!(has(&t, RED), "P100 read again at the top"); } + /// How many objects [`several_colors`] read on this thread. + fn several_reads() -> usize { + SEVERAL_COLORS_READS.with(std::cell::Cell::get) + } + + /// Whether more than one color is used ([`Session::several_colors_used`]), checked against the + /// length of `recolor.colors`'s list, with how many objects the answer read. + fn several(s: &mut Session, what: &str) -> (bool, usize) { + let before = several_reads(); + let several = s.several_colors_used(); + let reads = several_reads() - before; + let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len); + assert_eq!(several, listed > 1, "{what}: {listed} colors listed"); + (several, reads) + } + + /// The Recolor quick action asks on every change whether the selection uses more than one + /// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included, + /// and the objects are read only until a second color turns up. + #[test] + fn several_colors_stop_at_the_second_color() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids: Vec = (0..30) + .map(|i| { + let id = + s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + id + }) + .collect(); + s.execute("select.all", &json!({})).unwrap(); + assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read"); + // A blue object in the middle: the objects are read up to it, from either end. + s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap(); + let (found, reads) = several(&mut s, "a blue in the middle"); + assert!(found && matches!(reads, 15 | 16), "{reads} objects read"); + s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap(); + assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color"); + s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap(); + assert!(!several(&mut s, "the red ones").0); + s.execute("select.none", &json!({})).unwrap(); + assert!(several(&mut s, "Select All's objects").0); + + // A red object filled with a pattern too: its tile's color counts. + for (tile, expect) in [(BLUE, true), (RED, false)] { + let filled = NodeId(ids[1]); + s.edit("t", |d, _| { + let art = square(d, 0.0, Paint::solid(tile)); + d.patterns.retain(|p| p.name != "Tile"); + d.patterns.push(PatternDef::new("Tile", vec![art])); + if let Some(n) = d.node_mut(filled) { + n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap(); + assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}"); + } + } + /// A pattern tile's symbol instances charge the same limit as the art around it. #[test] fn pattern_tiles_charge_the_symbol_limit() { diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index cd2f804331..ed290b84fc 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1753,6 +1753,29 @@ fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact } } +/// Joins whole shape `pc`, whose matches `ms` are near ones in faces other than `l`'s alone, to line +/// `l` by its near matches among the glyphs of `l`'s face in `indexes`: the 256 glyphs closest to a +/// shape in proportion can all be glyphs of other faces drawn alike (a period, a dot). Those +/// matches when the shape joins, `None` when it does not (`l` unchanged). +fn join_in_line_face(l: &mut Line, pc: &Piece, ms: &[GlyphMatch], indexes: &[RetypeIndex], tolerance: f64) -> Option> { + let face = l.face.id(); + if ms.iter().any(|m| m.exact || m.face.id() == face) { + return None; + } + let fill = pc.filled.then_some(pc.nonzero); + let own: Vec = indexes + .iter() + .flat_map(|ix| { + let found = ix.near_matches_in(&pc.path, tolerance, face); + match fill { + Some(nonzero) => found.iter().filter_map(|m| ix.painted_agrees(m, &pc.path, nonzero, tolerance)).collect(), + None => found, + } + }) + .collect(); + join(l, pc, &own).then_some(own) +} + /// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour /// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is /// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as @@ -1886,14 +1909,17 @@ fn retype(s: &mut Session, p: &Value) -> Result { extra.push(f); } } - if !extra.is_empty() { + let indexes: Vec = if extra.is_empty() { + vec![index] + } else { // Near matching spends an index's comparison budget, so with a tolerance the // candidates are indexed again for this pass. let first = if tolerance > 0.0 { build(cands) } else { index }; - let others: Vec = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect(); - let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect(); - found = match_pieces(&pieces, &groups, &all, tolerance); - } + let mut all = vec![first]; + all.extend(extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec()))); + found = match_pieces(&pieces, &groups, &all.iter().collect::>(), tolerance); + all + }; // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit // them closest in all (the least leftover distance summed over those shapes), so every @@ -1949,11 +1975,19 @@ fn retype(s: &mut Session, p: &Value) -> Result { for ms in parts { // The part's candidates in the face most shapes fit (see `ranked`). let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id()); - let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); - let joined = match lines.last_mut() { + let mut cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + let mut joined = match lines.last_mut() { Some(l) if open => join(l, pc, &cands), _ => false, }; + if !joined + && open + && parts.len() == 1 + && let Some(own) = lines.last_mut().and_then(|l| join_in_line_face(l, pc, ms, &indexes, tolerance)) + { + joined = true; + cands = own; + } // A part that joined a line, perhaps as a mark, that is also another character, in // that face or else in the face most shapes fit of those it is a character in: the // character, should a split leave the part first on a line ([`verified`]). Kept by diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index 60218b8b4a..a239baafdd 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -149,6 +149,10 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { db.add_font(named_copy(true, (FAMILY, "Regular", "Version 2.000", "VersiontestSans-Regular")).unwrap()); assert_eq!(db.face(FAMILY, "Regular").unwrap().version, "Version 1.000"); let mut s = session(); + // Live type in the family puts the font among those compared first. Added last, after the + // bundled fonts and however many faces craft-fonts supplies, it can fall past the fonts + // Retype compares (`MAX_FACES`). + s.execute("text.create", &json!({"x": 40, "y": 300, "text": "live", "size": 40, "font": FAMILY, "style": "Regular"})).unwrap(); let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kg", "size": 40, "font": "Inter", "style": "Regular"})); s.execute("select.set", &json!({"ids": [inter]})).unwrap(); let r = query(&mut s, json!({"count": 96}), &db); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5f89bc1284..d60d292480 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -102,10 +102,12 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font}; // The comma below of Source Sans 3 is only marks there, and a modifier letter in this face. vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap()); + // Named, so it is among the fonts compared first, however many faces are loaded before it. + let fonts = json!([SPACING_COMMA_FAMILY]); let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"fonts": fonts})).unwrap(); assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}"); assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); // After a base, it joins the line as the mark; moved off its base, the split leaves it first, @@ -115,7 +117,7 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"fonts": fonts})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}"); assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); } @@ -1099,7 +1101,9 @@ fn lines_that_do_not_stack_as_a_paragraph_stay_apart() { s.execute("select.set", &json!({"ids": [a]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}"); - assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}"); + let fonts = r["fonts"].as_array().unwrap(); + assert!(!fonts.is_empty(), "{r}"); + assert!(fonts.iter().all(|f| f["area"] == json!(false)), "{r}"); } #[test] @@ -1918,16 +1922,24 @@ fn lines_in(s: &Session, g: u64) -> Vec { lines_in_family(s, g, None) } -/// [`lines_in`] with the face of the first glyph's match in `family` when given. +/// [`lines_in`] with the face of the first glyph's match in `family` when given. The family is +/// compared first, as `type.retype`'s `fonts` puts it, so the faces loaded before it cannot leave it +/// out of the fonts Retype compares. fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec { let d = &s.doc().unwrap().doc; let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces); let db = vectorcraft_text::FontDb::global(); let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); - let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted); + let fonts: Vec = family.into_iter().map(str::to_string).collect(); + let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &fonts), &wanted); let first = index.matches(&pieces[0].path); - let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id(); + let face = match family { + Some(f) => first.iter().find(|m| m.face.family == f).unwrap_or_else(|| panic!("the first glyph matches no glyph of {f}")), + None => &first[0], + } + .face + .id(); let mut lines: Vec = vec![]; for pc in &pieces { let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs new file mode 100644 index 0000000000..bf15cc340e --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -0,0 +1,233 @@ +//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for +//! print-and-cut work (stickers, labels). + +use serde_json::{Value, json}; +use vectorcraft_geom::{Rect, Vec2, rotate_deg}; + +use super::edit::selected_roots; +use super::object::group_nodes; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or}; +use crate::EngineError; +use vectorcraft_doc::{Node, Scaling}; + +const CMD: &str = "object.stepAndRepeat"; +const MAX_CELLS: usize = 10_000; +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "object.stepAndRepeat", + "Step and Repeat…", + ["Object", "Transform"], + None, + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + has_selection, + step_and_repeat + )] +} + +/// Which cells of the grid are turned by 180°. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Alternate { + None, + Columns, + Rows, +} + +/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first +/// cell's, and whether its copy is turned by 180° about the cell's center. +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Cell { + pub row: usize, + pub col: usize, + pub dx: f64, + pub dy: f64, + pub turned: bool, +} + +/// How many items of `size` with `gap` between them fit in `room` (all at least 0). +pub fn fit_count(room: f64, size: f64, gap: f64) -> usize { + if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS { + return 0; + } + (((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize +} + +/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh` +/// inside `margin` on every side. +pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) { + let m = margin.max(0.0); + (fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx)) +} + +/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy` +/// between rows, in reading order. +pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec { + (0..rows) + .flat_map(|row| (0..cols).map(move |col| (row, col))) + .map(|(row, col)| Cell { + row, + col, + dx: col as f64 * (w + gx), + dy: row as f64 * (h + gy), + turned: match alt { + Alternate::None => false, + Alternate::Columns => col % 2 == 1, + Alternate::Rows => row % 2 == 1, + }, + }) + .collect() +} + +fn count_param(p: &Value, key: &str) -> Result { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(1), + Some(v) => v + .as_u64() + .filter(|n| (1..=MAX_CELLS as u64).contains(n)) + .map(|n| n as usize) + .ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))), + } +} + +fn sheet_param(p: &Value) -> Result> { + let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) }; + let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number"))); + let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?); + if w <= 0.0 || h <= 0.0 { + return Err(bad(CMD, "`sheet` needs a positive width and height")); + } + Ok(Some(Rect::new(x, y, x + w, y + h))) +} + +fn step_and_repeat(s: &mut Session, p: &Value) -> Result { + check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?; + check_switches(p, &["patterns"], CMD)?; + let fill = switch_or(p, "fill", false, CMD)?; + let alt = match p.get("rotate").filter(|v| !v.is_null()) { + None => Alternate::None, + Some(v) => match v.as_str() { + Some("none") => Alternate::None, + Some("columns") => Alternate::Columns, + Some("rows") => Alternate::Rows, + _ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")), + }, + }; + let gap = super::f64_or(p, "gap", 0.0); + let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap)); + let margin = super::f64_or(p, "margin", 0.0); + if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { + return Err(bad(CMD, "gaps and margin must be finite")); + } + if margin < 0.0 { + return Err(bad(CMD, "`margin` must be 0 or more")); + } + let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) }; + let sheet = sheet_param(p)?; + let mut roots = selected_roots(s)?; + if roots.is_empty() { + return Err(EngineError::Other("nothing selected".into())); + } + let d = &s.doc()?.doc; + let cut = match p.get("cutId").filter(|v| !v.is_null()) { + None => None, + Some(v) => { + let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?); + let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| { + let mut found = false; + n.walk(&mut |c| found |= c.id == id); + found + }); + if !held { + return Err(bad(CMD, "`cutId` must be part of the selection")); + } + Some(id) + } + }; + let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]); + let b = d.bounds_of(&measured, false); + let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?; + let (w, h) = (b.width(), b.height()); + if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(EngineError::Other("the selection has no area to repeat".into())); + } + if w + gx <= EPS || h + gy <= EPS { + return Err(bad(CMD, "a negative gap must be smaller than the width or height it is between")); + } + let anchor = if fill { + let sheet = sheet.or_else(|| { + let c = d.bounds_of(&roots, false).unwrap_or(b).center(); + d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect) + }); + let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?; + Some((sheet, margin.max(0.0))) + } else { + None + }; + let (rows, cols) = match anchor { + Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + None => (rows, cols), + }; + if rows == 0 || cols == 0 { + return Err(EngineError::Other("the selection does not fit the sheet".into())); + } + if rows.saturating_mul(cols) > MAX_CELLS { + return Err(bad(CMD, format!("more than {MAX_CELLS} copies"))); + } + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let cells = layout(w, h, gx, gy, rows, cols, alt); + let center = b.center().to_vec2(); + let place = |c: &Cell| -> Affine { + let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); + if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } + }; + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + let ids = s.edit("Step and Repeat", |d, sel| { + if roots.len() > 1 { + roots = vec![group_nodes(d, &roots)?]; + } + // Every copy is made first, and all of them go in with one insertion. + let originals: Vec<(NodeId, Node)> = roots.iter().filter_map(|id| d.node(*id).map(|n| (*id, n.clone()))).collect(); + let mut lists: Vec<(NodeId, Vec)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect(); + let mut copied: Vec = vec![]; + let mut first = Affine::IDENTITY; + for c in &cells { + let m = place(c); + if c.row == 0 && c.col == 0 { + first = m; + continue; + } + for ((_, original), (_, list)) in originals.iter().zip(lists.iter_mut()) { + let mut n = d.reid(original); + n.transform(m, sc); + super::object::keep_pixel_aligned(&mut n, sc); + copied.push(n.id); + list.push(n); + } + } + if !copied.is_empty() { + // The copy of the last cell goes directly above its original and the first cell's on top. + for (_, list) in &mut lists { + list.reverse(); + } + d.insert_beside(lists, false)?; + super::typecmd::refresh_bounds_of(d, &copied); + } + if first != Affine::IDENTITY { + for id in &roots { + if let Some(n) = d.node_mut(*id) { + n.transform(first, sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + let mut out: Vec = roots.clone(); + out.extend(copied); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "rows": rows, "columns": cols, "count": ids.len() })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs new file mode 100644 index 0000000000..4d807f7d8d --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -0,0 +1,218 @@ +use serde_json::json; + +use super::*; + +const A4: (f64, f64) = (210.0, 297.0); + +#[test] +fn fills_a4_with_50_by_30_items_and_3_gap() { + assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4)); + assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3)); + assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0)); +} + +#[test] +fn layout_places_cells_at_the_pitch_and_alternates_rotation() { + let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns); + assert_eq!(c.len(), 36); + let at = |r: usize, k: usize| c[r * 4 + k]; + assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0)); + assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0)); + assert_eq!(c.iter().filter(|c| c.turned).count(), 18); + assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned); + let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows); + assert_eq!(rows.iter().map(|c| c.turned).collect::>(), [false, false, true, true, false, false]); + assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned)); +} + +fn setup() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + (s, id) +} + +fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { + let (mut s, _) = setup(); + let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s)); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap(); + assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3))); + assert_eq!(undo_steps(&s), steps + 1); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0)); + assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.len(), before.artboards.len()); + assert!(d.node(NodeId(ids[0])).is_some()); + assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); +} + +#[test] +fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36))); + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap(); + assert_eq!(r["count"], json!(24)); + let first = r["ids"][0].as_u64().unwrap(); + assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0)); +} + +#[test] +fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3))); + assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0)); + assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0)); + assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0)); +} + +#[test] +fn alternate_columns_turn_by_180_degrees_about_the_cell_center() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap(); + let b0 = bounds(&s, id); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1])); + assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6); + assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6); + let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind); + assert_ne!(tri(&s, ids[0]), tri(&s, ids[1])); +} + +#[test] +fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() { + let (mut s, art) = setup(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap(); + assert_eq!(r["count"], json!(3)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. })); + let mut paths = 0; + n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(paths, 2); + } +} + +#[test] +fn rejects_bad_params_and_a_selection_that_does_not_fit() { + let (mut s, _) = setup(); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err()); + assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err()); + assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err()); + let mut e = Session::new(); + e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert!(e.execute(CMD, &json!({})).is_err()); +} + +#[test] +fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() { + let (mut s, _) = setup(); + let steps = undo_steps(&s); + assert!(s.execute(CMD, &json!({"fill": true, "margin": -5})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": -50})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 3, "columns": 1, "gapY": -40})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "gap": -50})).is_err()); + assert_eq!(undo_steps(&s), steps, "a refusal records no undo step"); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": -10})).unwrap(); + assert_eq!(bounds(&s, r["ids"][1].as_u64().unwrap()), (40.0, 0.0, 90.0, 30.0), "a gap above minus the width overlaps neighbors"); +} + +#[test] +fn copies_go_in_with_one_walk_of_the_document_whatever_the_count() { + let walks = |columns: u64| { + let (mut s, _) = setup(); + for i in 0..50 { + s.execute("shape.rectangle", &json!({"x": 0, "y": 100 + i, "width": 5, "height": 5})).unwrap(); + } + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let before = vectorcraft_doc::tree_walks(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": columns, "gap": 1})).unwrap(); + assert_eq!(r["count"], json!(columns)); + vectorcraft_doc::tree_walks() - before + }; + assert_eq!(walks(40), walks(2), "the walks of the document do not grow with the number of copies"); +} + +#[test] +fn the_last_cells_copy_sits_directly_above_the_original() { + let (mut s, id) = setup(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 1})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + let order: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(order, [id, ids[2], ids[1]]); +} + +#[test] +fn fill_ignores_explicit_counts() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4))); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); +} + +#[test] +fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() { + let gap = |aligned: bool| { + let (mut s, id) = setup(); + if aligned { + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + } + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1])); + (c.0 - a.2, c.0 - a.0) + }; + assert!((gap(false).0 - 0.5).abs() < 1e-9); + let pitch = gap(true).1; + assert!((pitch - pitch.round()).abs() < 1e-9); +} + +#[test] +fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { + let first_x = |sheet: Option| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let mut p = json!({"fill": true, "cutId": cut}); + if let Some(sh) = sheet { + p["sheet"] = sh; + } + let r = s.execute(CMD, &p).unwrap(); + bounds(&s, r["ids"][0].as_u64().unwrap()).0 + }; + let default = first_x(None); + let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100}))); + assert!((explicit - default - 100.0).abs() < 1e-9); +} diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index 9ff48848af..ade875b4c9 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -4,6 +4,8 @@ //! resolves, for each area text object, the outlines of the wrap objects above it into //! `TextObject::wrap` (text space); the layout engine subtracts them from each line's span. +use std::collections::{HashMap, HashSet}; + use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap}; @@ -17,7 +19,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Text Wrap"], None, - "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}", + "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a selected type object with another selected object above it in its layer is the text to wrap, not a wrap object, and loses a wrap it had; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids (the wrap objects), warning? (no area type lies below any of them)}", has_selection, make ), @@ -27,13 +29,16 @@ pub fn specs() -> Vec { "Text Wrap Options…", ["Object", "Text Wrap"], None, - "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", + "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects, leaving out the type selected below them as Make does (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", has_selection, options ), ] } +/// The warning Make gives when no area type lies below any of its wrap objects in their layer. +pub const NO_AREA_TYPE_BELOW: &str = "Text Wrap: no area type lies below these objects in their layer, so no text wraps around them. Move the objects above the area type with Object › Arrange › Bring to Front. Point type does not wrap."; + /// The Offset a wrap object takes, in points. pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive = -1000.0..=1000.0; @@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result { Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? }) } +/// The type objects of `ids` that lie below another of `ids` in their layer: the text Make wraps +/// when the wrap objects and the type are selected together. Make leaves them out of the wrap +/// objects, and takes the wrap off any of them that has one. +fn type_to_wrap(d: &Document, ids: &[NodeId]) -> HashSet { + let wanted: HashSet = ids.iter().copied().collect(); + // One pass in paint order: each selected type object with its layer and place, and the place of + // the topmost selected object other than a layer in each layer. + let mut texts = vec![]; + let mut top: HashMap = HashMap::new(); + let mut at = 0usize; + for (layer, l) in d.layers.iter().enumerate() { + l.walk(&mut |n| { + if wanted.contains(&n.id) { + match n.kind { + NodeKind::Layer { .. } => {} + NodeKind::Text(_) => { + texts.push((n.id, layer, at)); + top.insert(layer, at); + } + _ => { + top.insert(layer, at); + } + } + } + at += 1; + }); + } + texts.into_iter().filter(|(_, layer, at)| top.get(layer).is_some_and(|t| t > at)).map(|(id, _, _)| id).collect() +} + fn make(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?; let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?; - s.edit("Make Text Wrap", |d, _| { - for id in &ids { - let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; - if matches!(n.kind, NodeKind::Layer { .. }) { + let (objects, text, changed) = { + let d = &s.doc()?.doc; + let text = type_to_wrap(d, &ids); + let objects: Vec = ids.iter().copied().filter(|i| !text.contains(i)).collect(); + for id in &objects { + if d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. })) { return Err(EngineError::Other("layers can't be wrap objects".into())); } - n.extras_mut().wrap = Some(w); } - Ok(()) - })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) + let changed = objects.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap != Some(w))) + || text.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap.is_some())); + (objects, text, changed) + }; + if changed { + s.edit("Make Text Wrap", |d, _| { + for id in &objects { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = Some(w); + } + for id in &text { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = None; + } + Ok(()) + })?; + } + let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::>() }); + let mut wraps = false; + vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id))); + if !wraps { + out["warning"] = json!(NO_AREA_TYPE_BELOW); + } + Ok(out) } fn release(s: &mut Session, p: &Value) -> Result { @@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result { fn options(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.options")?; - let current = { + // The type selected below the wrap objects is the text they wrap, as in Make. + let (ids, current) = { let d = &s.doc()?.doc; - ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default() + let text = type_to_wrap(d, &ids); + let ids: Vec = ids.into_iter().filter(|i| !text.contains(i)).collect(); + let current = ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default(); + (ids, current) }; if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) { return Ok(json!({ "offset": current.offset, "invert": current.invert })); } let w = wrap_param(p, current, "object.textWrap.options")?; + let changed = { + let d = &s.doc()?.doc; + ids.iter().any(|i| d.node(*i).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. }) && n.extras().wrap != Some(w))) + }; + if !changed { + return Ok(json!({ "offset": w.offset, "invert": w.invert })); + } s.edit("Text Wrap Options", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) @@ -287,6 +353,95 @@ mod tests { assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true})); } + fn wrap_of(s: &Session, id: u64) -> Option { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap + } + + fn area_type(s: &mut Session) -> u64 { + s.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(300), "size": 12, "area": {"width": 400, "height": 400}})) + .unwrap()["id"] + .as_u64() + .unwrap() + } + + fn ellipse(s: &mut Session) -> u64 { + s.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap() + } + + /// Make with the wrap object and the area type below it selected together wraps the type: the + /// type is the text to wrap, not another wrap object (#3211). + #[test] + fn make_with_the_area_type_selected_wraps_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let t = area_type(&mut s); + let plain = lines(&s, t); + let c = ellipse(&mut s); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(r, json!({"ids": [c]}), "{r}"); + assert!(wrap_of(&s, c).is_some()); + assert!(wrap_of(&s, t).is_none(), "the area type became a wrap object"); + assert_ne!(lines(&s, t), plain, "the area type did not wrap"); + // Make again with the same options changes nothing and records no undo step. + let steps = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("object.textWrap.make", &json!({})).unwrap(), json!({"ids": [c]})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // Text Wrap Options with both still selected sets the wrap object's options only, and the + // type keeps wrapping; the same options again record no undo step. + let wrapped = lines(&s, t); + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap()["offset"], json!(30.0)); + assert_eq!(wrap_of(&s, c).map(|w| w.offset), Some(30.0)); + assert!(wrap_of(&s, t).is_none(), "Options made the area type a wrap object"); + assert_ne!(lines(&s, t), wrapped, "the type did not follow the new offset"); + assert_ne!(lines(&s, t), plain); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("edit.undo", &json!({})).unwrap(); + // One undo takes the wrap off again. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(wrap_of(&s, c).is_none()); + assert_eq!(lines(&s, t), plain); + } + + /// Make with the object below the area type warns that no text wraps. After Bring to Front, + /// Make with both selected wraps the type, and the type that the first Make made a wrap object + /// is the text to wrap again (#3211). + #[test] + fn make_warns_when_the_object_is_below_the_type_and_wraps_after_bring_to_front() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let c = ellipse(&mut s); + let t = area_type(&mut s); + let plain = lines(&s, t); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(r["warning"], json!(super::NO_AREA_TYPE_BELOW), "{r}"); + assert_eq!(lines(&s, t), plain); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert!(r.get("warning").is_none(), "{r}"); + assert!(wrap_of(&s, t).is_none(), "the area type is still a wrap object"); + assert_ne!(lines(&s, t), plain, "the area type did not wrap"); + } + + /// Point type below a wrap object does not wrap, so Make warns. + #[test] + fn make_warns_over_point_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let p = s.execute("text.create", &json!({"x": 0, "y": 100, "text": "point type", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 80, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r, p]})).unwrap(); + let out = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(out["warning"], json!(super::NO_AREA_TYPE_BELOW), "{out}"); + assert!(wrap_of(&s, r).is_some()); + assert!(wrap_of(&s, p).is_none(), "the point type became a wrap object"); + } + #[test] fn text_flows_on_both_sides_of_a_centred_object() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 1c45d37f4c..f69f878e50 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -589,6 +589,18 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option { } } +/// Whether Create Outlines has a text object to convert in the selected roots. +pub fn can_create_outlines(s: &Session) -> bool { + use std::ops::ControlFlow::{Break, Continue}; + + let Ok(roots) = selected_roots(s) else { return false }; + let Some(st) = s.active() else { return false }; + roots + .iter() + .filter_map(|id| st.doc.node(*id)) + .any(|node| node.try_walk(&mut |child| if matches!(child.kind, NodeKind::Text(_)) { Break(()) } else { Continue(()) }).is_break()) +} + /// Text objects among `ids` and their descendants. fn text_ids(d: &Document, ids: &[NodeId]) -> Vec { text_ids_where(d, ids, |_| true) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 85a9e7510c..771c2d7f7d 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1854,9 +1854,12 @@ fn kana_style_and_roman_italics_are_character_features() { } assert_eq!(runs(&s), before); s.execute("text.setRangeStyle", &json!({"id": id, "featureChanges": ["-hkna", "-ital"]})).unwrap(); + let text = |s: &Session| runs(s).into_iter().map(|(t, _)| t).collect::(); + assert_eq!(text(&s), "かなAB"); assert!(runs(&s).iter().all(|(_, f)| f.is_empty()), "{:?}", runs(&s)); s.execute("charStyle.new", &json!({"name": "Kana", "attrs": {"features": ["hkna", "ital"]}})).unwrap(); s.execute("charStyle.apply", &json!({"name": "Kana", "id": id})).unwrap(); + assert_eq!(text(&s), "かなAB"); assert!(runs(&s).iter().all(|(_, f)| *f == ["hkna", "ital"]), "{:?}", runs(&s)); let e = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"features": ["ital=2"]}})).unwrap_err().to_string(); assert!(e.contains("unknown OpenType feature `ital=2`"), "{e}"); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index eb4afa3760..9fccd38bb4 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -257,6 +257,7 @@ fn gaps_set_word_spacing_and_leading() { // The layout uses the gap as the Desired word spacing; the paragraph keeps its own. assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]); assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]); + assert_eq!(t.plain_text(), "two words\nthree more words", "the runs hold the text"); assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs); assert_block(&t); assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room"); @@ -850,6 +851,7 @@ fn a_range_leading_change_with_block_on_moves_the_line_gap() { let t = text(&s, id); assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert_eq!(t.plain_text(), "BIG\na much longer second line\nmid one", "the runs hold the text"); assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); // Reset Panel's form: the leading is set and Block keeps the line gap. s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..228d23a0f0 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -5,7 +5,9 @@ use super::{NodeId, Value, cmd, find_command}; /// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on /// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art /// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none. -pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ +pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [ + "edit.copy", + "edit.cut", "edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack", @@ -35,7 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 35] = [ +const REPLAY_ONLY: [(&str, &str); 37] = [ + ("edit.copy", "artboard"), + ("edit.cut", "artboard"), ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -118,8 +122,8 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ /// Does command `id`, run on its own, first apply the edit the active tool is computing on /// another thread and the input held for it ([`Session::finish_tool_edit`])? Every command that /// can edit, select, save or give a document a new revision does; queries that only read do not -/// (`commands_that_do_not_wait_for_a_tool_edit_change_no_document` in the command sweep checks -/// them). A frontend that adds params from +/// (`every_command_with_junk_params` and `commands_that_do_not_wait_for_a_tool_edit_change_no_document` +/// in the command sweep check them). A frontend that adds params from /// its own state (the active artboard) applies them first itself. pub fn waits_for_tool_edit(id: &str) -> bool { find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id)) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 39be553eb6..88aee55d33 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -203,11 +203,23 @@ pub struct DocState { /// The selected objects as [`crate::Session::select`] last checked them or the proxies last /// read them, with the document they were checked in ([`SelectionRecord`]). Not saved. pub(crate) selection_record: Option, + /// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live + /// Paint group among, with the document it read. Not saved. + outside_live_paint: std::cell::RefCell>, /// The last move of the selected objects that changed nothing else they show ([`Moved`]). /// Not saved. pub moved: Option, } +/// Objects that hold no face or edge of a Live Paint group that counts with its group +/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as +/// [`EmptyArtboards::doc`] holds it. +#[derive(Clone, Debug)] +struct OutsideLivePaint { + doc: std::sync::Weak, + ids: Vec, +} + /// A move of whole objects that took document `from` to document `to`: each object the selection /// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and /// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine @@ -320,6 +332,8 @@ thread_local! { pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread. pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread. + pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -540,6 +554,7 @@ impl DocState { measured_in_own: None, inline_resolved: None, selection_record: None, + outside_live_paint: Default::default(), moved: None, } } @@ -558,6 +573,25 @@ impl DocState { pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> { self.selection_record().and_then(|r| r.paints.as_ref()) } + /// The faces and edges of Live Paint groups among `ids` that count with their group + /// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and + /// these objects, so the proxies and the Stroke panel, which ask on every frame, read the + /// objects' groups once after an edit. + pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet { + let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids; + if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) { + return std::collections::HashSet::new(); + } + #[cfg(test)] + LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1)); + let covered = cmd::live_paint_covered(&self.doc, ids); + if covered.is_empty() + && let Ok(mut k) = self.outside_live_paint.try_borrow_mut() + { + *k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() }); + } + covered + } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with /// 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 diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index d5641d9606..7daa75e0ae 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -312,6 +312,9 @@ pub(crate) struct ScriptGate { /// The paths of the open documents' files, as the documents held them when the person last /// opened or saved them. A document a script's command opened has none here. pub(crate) documents: Vec, + /// The real paths of the files the script's `File` objects hold open for writing, which a + /// command does not write: the run's end would write the objects' bytes over them. + pub(crate) held: Vec, /// The files the documents link to as the person left them when the run began: readable, not /// writable. pub(crate) linked: LinkedFiles, @@ -373,8 +376,11 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; + // A read-only file is not written over, also where a rename could replace it. + let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); + let held = matches!(access, Access::Write) && self.held.contains(&real); let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked + !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -1026,6 +1032,7 @@ mod tests { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: LinkedFiles::default(), also: None, }; @@ -1055,6 +1062,7 @@ mod tests { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: LinkedFiles::default(), also: None, }; @@ -1083,8 +1091,14 @@ mod tests { let later = base.join("outside/later.svg"); let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}"); - let gate = - ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; + let gate = ScriptGate { + read: ScriptScope::of_folder(&base.join("in")), + write: ScriptScope::default(), + documents: vec![], + held: vec![], + linked, + also: None, + }; std::fs::write(&later, "").unwrap(); let (read, write) = (|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok()); @@ -1115,6 +1129,7 @@ mod tests { read, write: ScriptScope::default(), documents: vec![], + held: vec![], linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]), also: None, }; @@ -1150,6 +1165,7 @@ mod tests { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: ScriptGate::real_files([doc.clone()]), also: None, }; @@ -1171,7 +1187,7 @@ mod tests { std::fs::write(&other, "").unwrap(); std::os::unix::fs::symlink(&secret, &link).unwrap(); let linked = ScriptGate::real_files([s(link.clone())]); - let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None }; + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], held: vec![], linked, also: None }; assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok()); std::fs::remove_file(&link).unwrap(); std::os::unix::fs::symlink(&other, &link).unwrap(); @@ -1180,6 +1196,38 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + #[test] + fn a_script_gate_does_not_write_over_a_read_only_file() { + let (base, _) = folders("gate-read-only"); + let out = base.join("out/kept.svg"); + std::fs::write(&out, "").unwrap(); + let gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join("out")), + documents: vec![], + held: vec![], + linked: LinkedFiles::default(), + also: None, + }; + let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); + let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); + // The open document's file is the only grant: no folder scope covers it. + let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() }; + let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok()); + assert_eq!(check(&kept), (true, true)); + assert!(document_write(), "an open document's file is written"); + let mut perms = std::fs::metadata(&out).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&out, perms.clone()).unwrap(); + assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); + assert!(check(&fresh).0, "a new file next to it is written"); + assert!(!document_write(), "also when it is an open document's file"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&out, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { @@ -1342,6 +1390,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_ignores_case_and_refuses_devices() { let (base, roots) = folders("case"); @@ -1423,6 +1472,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_refuses_a_stream_inside_a_write_root() { let (base, roots) = folders("streams"); diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index a2b9417461..d921008611 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,10 @@ pub struct Interaction { pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, + pub(crate) active_appearance_item: Option, + /// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's + /// revision, and this value stays the same until the interaction ends. + pub revision: u64, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an @@ -52,6 +56,19 @@ pub struct Interaction { pub keep_on_switch: bool, } +impl Interaction { + /// The active tool began it (a drag). + pub fn by_tool(&self) -> bool { + self.tool + } +} + +#[derive(Clone, Debug)] +pub(crate) struct PreviewAppearanceItem { + pub(crate) before: Option, + pub(crate) after: Option, +} + /// An interaction that a command from outside the tool set aside while it runs /// ([`crate::Session::outside_interaction`]). #[derive(Debug)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fb2115190c..5ceccf5920 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -39,6 +39,7 @@ pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_ pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; +pub use cmd::typecmd::can_create_outlines; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; @@ -383,6 +384,16 @@ pub struct Session { pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The one command a member of the script object model runs past + /// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the + /// member checked its options and its file. + pub(crate) script_unfenced: Option<&'static str>, + /// The printers the frontend lists for the next run, which takes them: `app.printerList` and + /// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here. + pub script_printers: Option, + /// The jobs the last run that printed to a printer prepared, until the frontend takes them + /// ([`Session::take_script_prints`]). + pub(crate) script_prints: Vec, /// The desktop app supplies each window by (document uid, runtime window identity) while a /// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center, /// and screen mode. This list is empty without windows (headless). diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1a7b78a91b..3c2f3e3299 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -438,6 +438,12 @@ pub struct Prefs { /// resetting the preferences keeps them; `tool.setOption` edits them. #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub tool_settings: std::collections::BTreeMap>, + /// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores + /// or updates a tool setting, 0 while none is stored and in preferences saved without one. + /// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog + /// field: resetting the preferences keeps it. + #[serde(default, skip_serializing_if = "is_zero")] + pub tool_settings_version: u32, /// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local /// library, not a Preferences dialog field: resetting the preferences keeps it; /// `perspective.presets.*` edit it. @@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35; /// The range of the Hold Shortcut Delay, in seconds. pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0); +/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]). +/// Version 1 makes Color Swatches the Shape Builder's Pick Color From. +pub const TOOL_SETTINGS_VERSION: u32 = 1; + +fn is_zero(v: &u32) -> bool { + *v == 0 +} + impl Prefs { + /// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before + /// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was + /// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a + /// version newer than this one is kept. + pub fn migrate_tool_settings(&mut self) { + if self.tool_settings_version < 1 + && let Some(saved) = self.tool_settings.get_mut("shapeBuilder") + && saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork") + { + saved.insert("pickColorFrom".into(), Value::from("swatches")); + } + self.mark_tool_settings_current(); + } + + /// Record that [`Self::tool_settings`], when any is stored, is in this version's form. + pub(crate) fn mark_tool_settings_current(&mut self) { + if !self.tool_settings.is_empty() { + self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION); + } + } + /// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences /// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own. pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value { @@ -672,6 +707,7 @@ impl Default for Prefs { use_registration_point_for_symbol: false, show_on_shape_creation: false, tool_settings: Default::default(), + tool_settings_version: 0, perspective_presets: vec![], blend_options: None, perspective_widget: Default::default(), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 25269a62e5..ec258ffae2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -49,6 +49,9 @@ //! `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. `undefined` throws. +//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at +//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an +//! error. A run that fails leaves the tool as it was. //! - `controlBounds` is the visible bounds, widened to take in the direction points of every path //! in the object. //! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), @@ -91,9 +94,11 @@ use vectorcraft_js::{ ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, }; -use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; +mod print; +mod save_open; mod tags; mod text; mod variables; @@ -172,7 +177,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// written yet, how many times each path's points went stale and each path as the run last saw its /// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each /// `DocumentPreset` the run made, with the size of the values they hold now and the most they may -/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out. +/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool +/// `app.selectTool` chose last. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -202,11 +208,16 @@ pub(super) struct State { editing: Cell>, locked: RefCell>, saving: Cell, + /// `app.userInteractionLevel` ([`save_open`]). + save_options: save_open::State, + /// The print option objects ([`print`]). + printing: print::State, text: text::TextState, presets: RefCell>>, preset_bytes: Cell, preset_limit: u64, vars: variables::Handles, + tool: Cell>, } impl State { @@ -219,6 +230,23 @@ impl State { pub(super) fn saving(&self) -> bool { self.saving.get() } + + /// Gives the run the printers the frontend listed (`None`: none can be printed to here), and + /// whether jobs an earlier run prepared still wait. + pub(super) fn start_printing(&self, printers: Option, waiting: bool) { + self.printing.start(printers, waiting); + } + + /// The jobs the run prepared for a printer, which the run no longer holds. + pub(super) fn take_prints(&self) -> Vec { + self.printing.take_jobs() + } + + /// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool + /// when the run ends without an error. + pub(super) fn chosen_tool(&self) -> Option<&'static str> { + self.tool.get() + } } /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every @@ -606,10 +634,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } /// The ids of a document's page items, topmost first, each group or compound path before the -/// objects in it ([`State`] keeps the lists of the last documents read). -fn page_items(h: &Host, st: &DocState) -> Rc> { +/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again, +/// after an edit or for another document, counts against the run's host-call allowance as a list +/// of that many objects does ([`list_charge`]). +fn page_items(h: &Host, st: &DocState) -> std::result::Result>, HostError> { if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { - return ids; + return Ok(ids); } fn walk(nodes: &[Arc], out: &mut Vec) { for n in nodes.iter().rev() { @@ -627,9 +657,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { } let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); + h.charge_call(list_charge(ids.len()))?; let ids = Rc::new(ids); keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); - ids + Ok(ids) +} + +/// The bytes a list of `n` objects that a collection builds again counts against the run's +/// host-call allowance, as the selection's list counts them ([`selection_of`]). +pub(super) fn list_charge(n: usize) -> u64 { + 16u64.saturating_mul(n as u64) } /// The objects directly in the layers and sublayers of a document: what deleting every page item @@ -844,12 +881,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. +/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together +/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s +/// changes are undone as well. fn on_doc( h: &Host, uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + atomically(h, |h| on_doc_steps(h, uid, keep_selection, f)) +} + +/// The steps of [`on_doc`]. +fn on_doc_steps( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer, activated) = { let s = h.session.borrow(); @@ -875,8 +924,8 @@ fn on_doc( restored = restore_layer(h, uid, layer.0, &layer.1); } } - // The document that was active is active again before any error is given: `f`'s error first, - // then the selection's, then the switch back's. + // The document that was active is active again before any error is given: an error that ends + // the run first, then `f`'s error, then the selection's, then the switch back's. let back = match active { Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), _ => Ok(()), @@ -888,12 +937,35 @@ fn on_doc( { st.activated = activated; } + first_error(r, restored, back) +} + +/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer +/// (`restored`) and the active document (`back`): an error that ends the run first, since a +/// script could catch `f`'s ordinary error, then the first error in that order. +fn first_error( + r: std::result::Result, + restored: std::result::Result<(), HostError>, + back: std::result::Result<(), HostError>, +) -> std::result::Result { + if !r.as_ref().is_err_and(ends_run) { + restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?; + } let v = r?; restored?; back?; Ok(v) } +/// Whether `e` ends the run, so that a script cannot catch it. +fn ends_run(e: &HostError) -> bool { + match e { + HostError::Abort(_) => true, + HostError::Marked { error, .. } => ends_run(error), + _ => false, + } +} + /// Marks stale the style objects whose styles a command the run ran removed or renamed. pub(super) fn after_kept_command(h: &Host) { text::styles::after_command(h); @@ -987,13 +1059,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts +/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a +/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files. fn path_key(p: &str) -> String { - let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); - let p = p.replace('\\', "/"); - let p = p.trim_end_matches('/').to_string(); - if windows { p.to_lowercase() } else { p } + let b = p.as_bytes(); + let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); + if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } /// `app.redraw()`: returns without changing anything. The app draws a frame between the run's @@ -1021,6 +1093,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(open)) } +/// The start of the tool names that scripts pass to `app.selectTool`, as the list at +/// gives them. +const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass + +/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the +/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's +/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own. +const TOOL_NAMES: &[(&str, &str)] = &[ + ("Select Tool", "selection"), + ("Direct Select Tool", "directSelection"), + ("Direct Object Select Tool", "groupSelection"), + ("Direct Lasso Tool", "lasso"), + ("Path Type Tool", "typeOnPath"), + ("Vertical Path Type Tool", "verticalTypeOnPath"), + ("Line Tool", "lineSegment"), + ("Shape Construction Regular Polygon Tool", "polygon"), + ("Shape Construction Star Tool", "star"), + ("Shape Construction Spiral Tool", "spiral"), + ("Brush Tool", "paintbrush"), + ("Freehand Tool", "pencil"), + ("Freehand Smooth Tool", "smooth"), + ("Freehand Erase Tool", "pathEraser"), + ("Corner Join Tool", "join"), + ("Knife Tool", "knife"), + ("New Twirl Tool", "twirl"), + ("Cyrstallize Tool", "crystallize"), + ("Planar Paintbucket Tool", "livePaintBucket"), + ("Planar Face Select Tool", "livePaintSelection"), + ("Mesh Editing Tool", "mesh"), + ("Gradient Vector Tool", "gradient"), + ("Crop Tool", "artboard"), + ("Slice Select Tool", "sliceSelection"), + ("Scroll Tool", "hand"), + ("Page Tool", "printTiling"), +]; + +/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the +/// list [`TOOL_NAME_PREFIX`] cites. +fn tool_named(name: &str) -> Option<&'static str> { + let tools = || vectorcraft_tools::catalog::all_tools(); + if let Some(t) = tools().find(|t| t.id == name || t.label == name) { + return Some(t.id); + } + let rest = name.strip_prefix(TOOL_NAME_PREFIX)?; + if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) { + return vectorcraft_tools::tool_info(id).map(|t| t.id); + } + tools().find(|t| t.label == rest).map(|t| t.id) +} + +/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The +/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar +/// does; the tool chosen last in a run is the one that counts. A name no tool has throws. +fn app_select_tool(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the tool name is too long".into())); + } + let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?; + h.dom.tool.set(Some(id)); + Ok(Data::Bool(true)) +} + /// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The /// strings are the ones /// @@ -1414,6 +1549,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { }) } +/// `documents.addDocumentNoUI(startupPreset)`: a new document from the New Document profile +/// `startupPreset` names, as `addDocument(startupPreset)` makes it, without the New Document +/// dialog. Arguments after `startupPreset` are ignored. +fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer { + docs_add_document(h, &a[..a.len().min(2)]) +} + /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are /// left out. The settings stay with the run, which hands the script an object of the @@ -1492,6 +1634,19 @@ fn preset_of(h: &Host, d: &Data) -> Option { (i < h.dom.presets.borrow().len()).then_some(i) } +/// `DocumentPreset.typename`: a `TypeError` for a preset from an earlier run, as its settings give. +fn preset_typename(h: &Host, a: &[Data]) -> Answer { + preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?; + Ok(text("DocumentPreset")) +} + +/// `DocumentPreset.toString()`: `[DocumentPreset]`, or a `TypeError` for a preset from an earlier +/// run. +fn preset_to_string(h: &Host, a: &[Data]) -> Answer { + preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?; + Ok(text("[DocumentPreset]")) +} + /// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one. fn preset_enum(key: &str) -> Option<&'static str> { Some(match key { @@ -1972,7 +2127,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { fn items_length(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?; Ok(num(float(n as u64))) } @@ -2013,7 +2168,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { r => r, }, Data::Number(n) => match position(*n) { - Some(i) => Ok(item_at(h, doc, i)), + Some(i) => item_at(h, doc, i), None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), r => r, @@ -2024,8 +2179,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } /// The object at position `i` of `pageItems`, or `undefined` past the end. -fn item_at(h: &Host, doc: Doc, i: usize) -> Data { - with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) +fn item_at(h: &Host, doc: Doc, i: usize) -> Answer { + with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { @@ -2037,7 +2192,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { /// The first object of `pageItems` named `name`, or `Not found`. fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { - let ids = page_items(h, st); + let ids = page_items(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -2049,7 +2204,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { Data::String(_) => items_by_name(h, a), Data::Number(n) => { let doc = items_doc(h, a)?; - match position(*n).map(|i| item_at(h, doc, i)) { + match position(*n).map(|i| item_at(h, doc, i)).transpose()? { None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), Some(d) => Ok(d), } @@ -2224,9 +2379,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and - // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // A value the getter reports for the item's opacity runs no command, unless the item is a graph + // mark or label whose graph keeps another opacity for its series or kind: then the opacity the + // item has is sent, and replaces the one the graph keeps. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. let (now, keeps_other) = with_doc(h, item.doc, |_, st| { @@ -2240,7 +2395,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if now.is_none() || keeps_other { refuse_protected_edit(h, item)?; } - set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) + set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)})) } /// The members of `BlendModes` with the blend mode each one names. @@ -2534,8 +2689,9 @@ struct Destination { /// The object a relative object of `move` or `duplicate` names: a page item or a layer of the /// same document as `item`. An object may go directly above or below itself: a copy goes there, as -/// `layer.move` puts copies, and a move there leaves the object where it is. -fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { +/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a +/// clipping path cannot go below it. +fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); @@ -2568,6 +2724,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: (parent, Some(target)) } }; + // The clipping path stays at the bottom of its clip group or clipping layer. Moving the + // clipping path below itself leaves it where it is. + if how == Placement::Below + && (target != item.id || copy) + && d.node(parent).is_some_and(crate::doc::Node::clips) + && d.position(target).is_some_and(|(_, i, _)| i == 0) + { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } @@ -2622,7 +2787,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } - let to = destination(h, item, arg(a, 1), arg(a, 2))?; + let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; if to.beside != Some(item.id) { place(h, item.doc, item.id, &to)?; } @@ -2663,7 +2828,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } None } - target => Some(destination(h, item, target, arg(a, 2))?), + target => Some(destination(h, item, target, arg(a, 2), true)?), }; let id = atomically(h, |h| { let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; @@ -2695,17 +2860,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (before, after) = with_doc(h, item.doc, |_, st| { - let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); - (at.map(|(_, i, _)| i), count) + // The Arrange commands keep a clipping path at the bottom of its parent and the art below the + // parent's ruler guides, so the item's place is counted among the art above the clipping path. + let (before, floor, art) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let at = d.position(item.id); + let parent = at.and_then(|(p, ..)| p); + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c)); + (at.map(|(_, i, _)| i), floor, art) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; - let top = i + 1 >= after; - let unchanged = match id { - "object.arrange.bringToFront" | "object.arrange.bringForward" => top, - _ => i == 0, - }; + let unchanged = i < floor + || match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art, + _ => i <= floor, + }; if !unchanged { edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; } @@ -2812,7 +2982,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - for (name, members) in ENUMS { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -2842,6 +3012,7 @@ fn classes(link: &Link) -> Vec { ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ("redraw", method(l, app_redraw), returns("undefined", &[])), + ("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])), ("undo", method(l, app_undo), returns("undefined", &[])), ("redo", method(l, app_redo), returns("undefined", &[])), ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), @@ -2849,6 +3020,8 @@ fn classes(link: &Link) -> Vec { ]); application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); + application.extend(save_open::application_members(l)); + application.extend(print::application_members(l)); application.extend(super::actions::app_members(l)); let preset = { let l = link.clone(); @@ -2858,8 +3031,8 @@ fn classes(link: &Link) -> Vec { new_preset(&h) }); let mut members = vec![ - ("typename".to_string(), typename_of("DocumentPreset"), typed("string")), - ("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])), + ("typename".to_string(), get(link, preset_typename), typed("string")), + ("toString".to_string(), method(link, preset_to_string), returns("string", &[])), ]; members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } @@ -2897,6 +3070,7 @@ fn classes(link: &Link) -> Vec { method(l, docs_add_document), returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), ), + ("addDocumentNoUI", method(l, docs_add_document_no_ui), returns("Document", &[("startupPreset", "string")])), ("toString", class_text("Documents"), returns("string", &[])), ]), Some(function(l, docs_at)), @@ -2926,10 +3100,10 @@ fn classes(link: &Link) -> Vec { ]); document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); - document.extend( - ["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)), - ); + document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m))); document.extend(variables::document_members(l)); + document.extend(save_open::document_members(l)); + document.extend(print::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); classes.push(class("Document", None, document, None)); classes.push(class( @@ -3039,6 +3213,8 @@ fn classes(link: &Link) -> Vec { classes.extend(colors::classes(l)); classes.extend(text::classes(l)); classes.extend(variables::classes(l)); + classes.extend(save_open::classes(l)); + classes.extend(print::classes(l)); classes.push(class( "Layer", None, @@ -3066,6 +3242,24 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + /// A stop from putting back the selection or the active document is not hidden by the edit's + /// own error, which a script could catch; ordinary errors keep their order. + #[test] + fn an_edit_gives_a_stop_ahead_of_its_own_error() { + let error = |m: &str| HostError::Error(m.into()); + let stop = || HostError::Abort("stop".into()); + let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 }; + assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop())); + assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop())); + assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked())); + assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop())); + // The edit's own stop comes first, and with no stop the edit's error does. + assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into()))); + assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit"))); + assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection"))); + assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1)); + } + #[test] fn page_item_lists_are_kept_for_several_documents() { let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..03ec3812a6 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -15,7 +15,9 @@ //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden -//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing +//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked +//! artboard. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -106,6 +108,18 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } +/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or +/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one. +fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> { + if !editable(&st.doc, id) { + return Err(cannot_edit(id)); + } + if super::on_locked_artboard(h, st, id) { + return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))); + } + Ok(()) +} + /// The path `d` names, which must still be in its document. fn path_of(h: &super::Host, d: &Data) -> std::result::Result { let item = item_of(h, d)?; @@ -234,7 +248,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { forget_waiting_starts(h); @@ -246,15 +260,13 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); - let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, editable(d, item.id), aligned) + (pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); - } + refused?; *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { flush(h)?; @@ -337,15 +349,12 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which -/// must be one the user could edit. +/// must be one the user could edit ([`refuse_path_edit`]). /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); - if !ok { - return Err(cannot_edit(item.id)); - } + with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } @@ -367,16 +376,18 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { // ---- Document.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { +/// The ids of a document's paths, in the order of its page items. Building the list again counts +/// the page items it looks through against the run's host-call allowance. +fn path_items(h: &super::Host, st: &DocState) -> Result>, HostError> { if let Some(ids) = super::kept_list(&h.dom.paths, st) { - return ids; + return Ok(ids); } - let all = super::page_items(h, st); + let all = super::page_items(h, st)?; + h.charge_call(all.len() as u64)?; let ids: Rc> = Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); super::keep_list(&h.dom.paths, st, &ids); - ids + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -396,7 +407,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer { fn items_length(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -408,14 +419,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -434,18 +445,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let ids = path_items(h, st)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs new file mode 100644 index 0000000000..2e1d374cb1 --- /dev/null +++ b/crates/engine/src/script/dom/print.rs @@ -0,0 +1,1184 @@ +//! Printing in the script object model: `Document.print`, `PrintOptions` and its option classes, +//! `app.printPresetsList`, `app.printerList` and `app.PPDFileList`, as the help pages +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! An option object is an object of a host class whose properties the run keeps. A `PrintOptions` +//! holds its option objects by reference, so a change made to one after it was assigned is read +//! when `print` is called. Every value is checked when it is assigned; `print` maps the whole tree +//! into `file.print`'s settings before anything is written. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `print` with `jobOptions.file` writes a file, a `File` the script may write +//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the +//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. +//! - `print` without a file prepares a job for the printer `printerName` names, or for the +//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a +//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name +//! must be exactly the name of a printer the frontend listed for the run. Where the frontend lists +//! no printers for scripts (the web, a run without the app), `print` without a file throws. A run +//! prepares at most [`MAX_JOBS`] jobs, of at most [`MAX_SHEETS`] sheets and [`MAX_JOB_BYTES`] +//! together, and none while jobs of an earlier run still wait. A job for a printer is a PDF, so +//! `postScriptLevel` applies only to a file. +//! - Only the properties a script assigned apply; the others keep the settings `print` starts +//! from: the preset's when `printPreset` is assigned, otherwise the document's print settings +//! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as +//! the default its help page gives. +//! - A property the help pages list that is not mapped accepts the default its help page gives +//! and throws an error that says it is not available yet at any other value. +//! - `fitToPage` set to true wins over the scale factors and the tiling mode. +//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range +//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange` +//! replaces the range of the settings `print` starts from, which prints when those settings +//! print a range. +//! - An assigned `printArea` prints by artboard when the settings `print` starts from ignore the +//! artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. +//! - The format follows the name `jobOptions.file` gives, also when that name is a link to a file +//! with another extension. +//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the +//! settings `print` starts from. +//! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard +//! the document does not have, also with `printAllArtboards` true; when `printPreset` or +//! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is +//! not the name of an RGB or CMYK color profile (any case); and when `paperOptions.name` is not +//! the id or label of a paper `file.print` knows, or names a paper other than `custom` while +//! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, +//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked +//! name goes to `file.print` without the spaces around it. `PPDName` takes only the empty string. +//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. +//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects, +//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no +//! document open, as the help page +//! describes, and where the frontend lists no printers for scripts. `app.PPDFileList` is empty: +//! VectorCraft prints without PPD files. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_color::cms; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref, host_ref_parts}; + +use super::super::printing::{MAX_JOB_BYTES, MAX_JOBS, MAX_SHEETS, PreparedPrint, Printers}; +use super::save_open::{exactly, file_path, plain, refused}; +use super::{ + Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, class, command, command_kept, current, float, get, given, later, method, + named, num, on_doc, returns, text, this_doc, typed, whole, with_doc, +}; +use crate::cmd::flatten::FlattenOptions; + +/// The most option objects one run makes. +pub const MAX_OPTION_OBJECTS: usize = 256; +/// The largest scale factor `file.print` takes, in percent. +pub const MAX_PRINT_SCALE: f64 = 1000.0; +/// The error of `print` without `jobOptions.file` where the frontend lists no printers for scripts. +pub const NO_PRINTER: &str = "Printing to a printer is not available here: set jobOptions.file to print to a file"; +/// The error of `app.printerList` where the frontend lists no printers for scripts. +pub const NO_PRINTERS: &str = "Application.printerList is not available here"; +/// The error of `app.printerList` with no document open. +pub const PRINTERS_NEED_DOCUMENT: &str = "Application.printerList needs an open document"; +/// The error of `print` to the default printer when the system names none. +pub const NO_DEFAULT_PRINTER: &str = "There is no default printer: set PrintOptions.printerName"; +/// The error of `print` to a printer while jobs an earlier run prepared wait. +pub const PRINT_WAITING: &str = "A print job from an earlier script still waits for approval"; +/// The error of `print` to a printer with `postScriptLevel` assigned. +pub const POSTSCRIPT_TO_FILE: &str = "PostScript prints only to a file: set jobOptions.file"; +/// The error for an option object from an earlier run. +pub const STALE_OPTIONS: &str = "Stale print options"; +/// The error for a `Printer` object from an earlier run. +pub const STALE_PRINTER: &str = "Stale printer"; + +/// The option objects of the run: each one's class, as an index into [`CLASSES`], and the +/// properties the script assigned; the printers the frontend listed for the run, and the jobs the +/// run prepared for them. +#[derive(Default)] +pub(in crate::script) struct State { + objects: RefCell>, + printers: RefCell>, + /// Jobs an earlier run prepared wait to be sent or dropped. + waiting: Cell, + jobs: RefCell>, +} + +impl State { + pub(in crate::script) fn start(&self, printers: Option, waiting: bool) { + *self.printers.borrow_mut() = printers; + self.waiting.set(waiting); + } + + pub(in crate::script) fn take_jobs(&self) -> Vec { + std::mem::take(&mut *self.jobs.borrow_mut()) + } +} + +struct Options { + class: usize, + set: Vec<(&'static str, Data)>, +} + +const PRINT_COLOR_PROFILE: &[&str] = &["CUSTOMPROFILE", "PRINTERPROFILE", "OLDSTYLEPROFILE", "SOURCEPROFILE"]; +const PRINT_COLOR_INTENT: &[&str] = &["ABSOLUTECOLORIMETRIC", "PERCEPTUALINTENT", "RELATIVECOLORIMETRIC", "SATURATIONINTENT"]; +const PRINT_COLOR_SEPARATION_MODE: &[&str] = &["COMPOSITE", "HOSTBASEDSEPARATION", "INRIPSEPARATION"]; +const PRINT_ORIENTATION: &[&str] = &["AUTOROTATE", "LANDSCAPE", "PORTRAIT", "REVERSELANDSCAPE", "REVERSEPORTRAIT"]; +const PRINT_POSITION: &[&str] = &[ + "TRANSLATEBOTTOM", + "TRANSLATEBOTTOMLEFT", + "TRANSLATEBOTTOMRIGHT", + "TRANSLATECENTER", + "TRANSLATELEFT", + "TRANSLATERIGHT", + "TRANSLATETOP", + "TRANSLATETOPLEFT", + "TRANSLATETOPRIGHT", +]; +const PRINT_TILING: &[&str] = &["TILEFULLPAGES", "TILESINGLEFULLPAGE", "TILEIMAGEABLEAREAS"]; +const PRINT_ARTWORK_DESIGNATION: &[&str] = &["ALLLAYERS", "VISIBLELAYERS", "VISIBLEPRINTABLELAYERS"]; +const PRINTING_BOUNDS: &[&str] = &["ARTBOARDBOUNDS", "ARTWORKBOUNDS"]; +const PRINT_FONT_DOWNLOAD_MODE: &[&str] = &["DOWNLOADNONE", "DOWNLOADCOMPLETE", "DOWNLOADSUBSET"]; +const FONT_SUBSTITUTION_POLICY: &[&str] = &["SUBSTITUTEDEVICE", "SUBSTITUTEOBLIQUE", "SUBSTITUTETINT"]; +const PAGE_MARKS_TYPES: &[&str] = &["Japanese", "Roman"]; +const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]; +const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"]; +const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"]; + +/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from +/// [`super::save_open::ENUMS`]. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("PrintColorProfile", PRINT_COLOR_PROFILE), + ("PrintColorIntent", PRINT_COLOR_INTENT), + ("PrintColorSeparationMode", PRINT_COLOR_SEPARATION_MODE), + ("PrintOrientation", PRINT_ORIENTATION), + ("PrintPosition", PRINT_POSITION), + ("PrintTiling", PRINT_TILING), + ("PrintArtworkDesignation", PRINT_ARTWORK_DESIGNATION), + ("PrintingBounds", PRINTING_BOUNDS), + ("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE), + ("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY), + ("PageMarksTypes", PAGE_MARKS_TYPES), + ("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION), + ("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL), +]; + +/// What a property takes. +#[derive(Clone, Copy)] +enum Kind { + Bool, + /// A finite number from the first to the second. + Number(f64, f64), + /// A whole number from the first to the second. + Whole(u64, u64), + Text, + /// A value of the enumeration (its name and members); only the members in the last list are + /// available. + Choice(&'static str, &'static [&'static str], &'static [&'static str]), + /// An option object of the class named. + Child(&'static str), + File, +} + +/// The default a property reads as before it is assigned. +#[derive(Clone, Copy)] +enum Start { + None, + Bool(bool), + Num(f64), + Text(&'static str), + /// An enumerated value, by its member name. + Member(&'static str), +} + +impl Start { + fn value(self, kind: Kind) -> Data { + match (self, kind) { + (Start::Bool(b), _) => Data::Bool(b), + (Start::Num(n), _) => num(n), + (Start::Text(s), _) => text(s), + (Start::Member(m), Kind::Choice(e, ..)) => text(format!("{e}.{m}")), + _ => Data::Undefined, + } + } + + fn matches(self, kind: Kind, d: &Data) -> bool { + match (self, d) { + (Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Start::None, _) => false, + _ => self.value(kind) == *d, + } + } +} + +/// A property: its name, what it takes, its default, and whether `print` maps it. +struct Field { + name: &'static str, + kind: Kind, + start: Start, + mapped: bool, +} + +const fn f(name: &'static str, kind: Kind, start: Start) -> Field { + Field { name, kind, start, mapped: true } +} + +const fn kept(name: &'static str, kind: Kind, start: Start) -> Field { + Field { name, kind, start, mapped: false } +} + +struct Class { + name: &'static str, + fields: &'static [Field], +} + +const fn choice(e: &'static str, all: &'static [&'static str], ok: &'static [&'static str]) -> Kind { + Kind::Choice(e, all, ok) +} + +const PRINT_OPTIONS: Class = Class { + name: "PrintOptions", + fields: &[ + f("colorManagementOptions", Kind::Child("PrintColorManagementOptions"), Start::None), + f("colorSeparationOptions", Kind::Child("PrintColorSeparationOptions"), Start::None), + f("coordinateOptions", Kind::Child("PrintCoordinateOptions"), Start::None), + f("flattenerOptions", Kind::Child("PrintFlattenerOptions"), Start::None), + f("flattenerPreset", Kind::Text, Start::None), + f("fontOptions", Kind::Child("PrintFontOptions"), Start::None), + f("jobOptions", Kind::Child("PrintJobOptions"), Start::None), + f("pageMarksOptions", Kind::Child("PrintPageMarksOptions"), Start::None), + f("paperOptions", Kind::Child("PrintPaperOptions"), Start::None), + f("postScriptOptions", Kind::Child("PrintPostScriptOptions"), Start::None), + kept("PPDName", Kind::Text, Start::Text("")), + f("printerName", Kind::Text, Start::Text("")), + f("printPreset", Kind::Text, Start::None), + ], +}; + +const JOB: Class = Class { + name: "PrintJobOptions", + fields: &[ + f("artboardRange", Kind::Text, Start::Text("1-")), + kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)), + f("collate", Kind::Bool, Start::Bool(false)), + f("copies", Kind::Whole(1, 999), Start::Num(1.0)), + f( + "designation", + choice("PrintArtworkDesignation", PRINT_ARTWORK_DESIGNATION, PRINT_ARTWORK_DESIGNATION), + Start::Member("VISIBLEPRINTABLELAYERS"), + ), + f("file", Kind::File, Start::None), + kept("name", Kind::Text, Start::None), + f("printAllArtboards", Kind::Bool, Start::Bool(true)), + f("printArea", choice("PrintingBounds", PRINTING_BOUNDS, &["ARTBOARDBOUNDS"]), Start::Member("ARTBOARDBOUNDS")), + f("printAsBitmap", Kind::Bool, Start::Bool(false)), + f("reversePages", Kind::Bool, Start::Bool(false)), + ], +}; + +const COLOR: Class = Class { + name: "PrintColorManagementOptions", + fields: &[ + f("colorProfileMode", choice("PrintColorProfile", PRINT_COLOR_PROFILE, &["CUSTOMPROFILE", "SOURCEPROFILE"]), Start::Member("SOURCEPROFILE")), + f("intent", choice("PrintColorIntent", PRINT_COLOR_INTENT, PRINT_COLOR_INTENT), Start::Member("RELATIVECOLORIMETRIC")), + f("name", Kind::Text, Start::None), + ], +}; + +const SEPARATION: Class = Class { + name: "PrintColorSeparationOptions", + fields: &[ + f( + "colorSeparationMode", + choice("PrintColorSeparationMode", PRINT_COLOR_SEPARATION_MODE, &["COMPOSITE", "HOSTBASEDSEPARATION"]), + Start::Member("COMPOSITE"), + ), + f("convertSpotColors", Kind::Bool, Start::Bool(false)), + kept("inkList", Kind::Text, Start::None), + f("overPrintBlack", Kind::Bool, Start::Bool(false)), + ], +}; + +const COORDINATE: Class = Class { + name: "PrintCoordinateOptions", + fields: &[ + f("emulsion", Kind::Bool, Start::Bool(false)), + f("fitToPage", Kind::Bool, Start::Bool(false)), + f("horizontalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)), + f("orientation", choice("PrintOrientation", PRINT_ORIENTATION, PRINT_ORIENTATION), Start::Member("PORTRAIT")), + f("position", choice("PrintPosition", PRINT_POSITION, PRINT_POSITION), Start::Member("TRANSLATECENTER")), + f("tiling", choice("PrintTiling", PRINT_TILING, PRINT_TILING), Start::Member("TILESINGLEFULLPAGE")), + f("verticalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)), + ], +}; + +const FLATTENER: Class = Class { + name: "PrintFlattenerOptions", + fields: &[ + kept("clipComplexRegions", Kind::Bool, Start::Bool(false)), + kept("convertStrokesToOutlines", Kind::Bool, Start::Bool(false)), + kept("convertTextToOutlines", Kind::Bool, Start::Bool(false)), + kept("flatteningBalance", Kind::Number(0.0, 100.0), Start::Num(100.0)), + kept("gradientResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + f("overprint", choice("PDFOverprint", PDF_OVERPRINT, PDF_OVERPRINT), Start::Member("PRESERVEPDFOVERPRINT")), + kept("rasterizationResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + ], +}; + +const FONT: Class = Class { + name: "PrintFontOptions", + fields: &[ + kept("downloadFonts", choice("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE, &[]), Start::Member("DOWNLOADSUBSET")), + kept("fontSubstitution", choice("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY, &[]), Start::Member("SUBSTITUTEOBLIQUE")), + ], +}; + +const MARKS: Class = Class { + name: "PrintPageMarksOptions", + fields: &[ + kept("bleedOffsetRect", Kind::Text, Start::None), + f("colorBars", Kind::Bool, Start::Bool(false)), + kept("marksOffsetRect", Kind::Text, Start::None), + f("pageInfoMarks", Kind::Bool, Start::Bool(false)), + f("pageMarksType", choice("PageMarksTypes", PAGE_MARKS_TYPES, PAGE_MARKS_TYPES), Start::Member("Roman")), + f("registrationMarks", Kind::Bool, Start::Bool(false)), + f("trimMarks", Kind::Bool, Start::Bool(false)), + f("trimMarksWeight", Kind::Number(0.0, 1000.0), Start::Num(0.125)), + ], +}; + +const PAPER: Class = Class { + name: "PrintPaperOptions", + fields: &[ + f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("name", Kind::Text, Start::None), + kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("transverse", Kind::Bool, Start::Bool(false)), + f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + ], +}; + +const POSTSCRIPT: Class = Class { + name: "PrintPostScriptOptions", + fields: &[ + kept("binaryPrinting", Kind::Bool, Start::Bool(false)), + kept("compatibleShading", Kind::Bool, Start::Bool(false)), + kept("forceContinuousTone", Kind::Bool, Start::Bool(false)), + kept("imageCompression", choice("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION, &[]), Start::Member("IMAGECOMPRESSIONNONE")), + f("negativePrinting", Kind::Bool, Start::Bool(false)), + f("postScriptLevel", choice("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL, &["PSLEVEL2", "PSLEVEL3"]), Start::Member("PSLEVEL2")), + kept("shadingResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + ], +}; + +/// The option classes, `PrintOptions` first. +const CLASSES: &[Class] = &[PRINT_OPTIONS, JOB, COLOR, SEPARATION, COORDINATE, FLATTENER, FONT, MARKS, PAPER, POSTSCRIPT]; + +fn class_index(name: &str) -> Option { + CLASSES.iter().position(|c| c.name == name) +} + +fn not_available(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class}.{name} is not available yet")) +} + +/// A new option object of class `class`. +fn create(h: &Host, class: usize) -> Answer { + let mut objects = h.dom.printing.objects.borrow_mut(); + if objects.len() >= MAX_OPTION_OBJECTS { + return Err(HostError::Range(format!("a script can make at most {MAX_OPTION_OBJECTS} print option objects in a run"))); + } + objects.push(Options { class, set: Vec::new() }); + let slot = u64::try_from(objects.len() - 1).unwrap_or(u64::MAX); + Ok(host_ref(CLASSES[class].name, &[float(h.run), float(slot)])) +} + +/// The slot of the option object `d` of class `class`, made in this run. +fn slot_of(h: &Host, d: &Data, class: usize) -> std::result::Result { + let name = CLASSES[class].name; + let wrong = || HostError::Type(format!("this is not a {name}")); + let (c, handle) = host_ref_parts(d).ok_or_else(wrong)?; + if c != name { + return Err(wrong()); + } + let [run, slot] = handle.as_slice() else { return Err(wrong()) }; + let stale = || HostError::Error(STALE_OPTIONS.into()); + if whole(*run) != Some(h.run) { + return Err(stale()); + } + let slot = whole(*slot).and_then(|s| usize::try_from(s).ok()).ok_or_else(stale)?; + match h.dom.printing.objects.borrow().get(slot) { + Some(o) if o.class == class => Ok(slot), + _ => Err(stale()), + } +} + +/// The value `d` assigned to `field` of `class` stores, or `None` when it unsets it. +fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Result, HostError> { + let what = format!("{}.{}", class.name, field.name); + if matches!(d, Data::Undefined) || (matches!(d, Data::Null) && matches!(field.kind, Kind::Child(_) | Kind::File)) { + return Ok(None); + } + if !field.mapped { + return if field.start.matches(field.kind, d) { Ok(None) } else { Err(not_available(class.name, field.name)) }; + } + match field.kind { + Kind::Bool => match d { + Data::Bool(_) => {} + _ => return Err(HostError::Type(format!("{what} must be true or false"))), + }, + Kind::Number(lo, hi) => match d { + Data::Number(n) if n.is_finite() => { + if !(lo..=hi).contains(n) { + return Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))); + } + } + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }, + Kind::Whole(lo, hi) => match d { + Data::Number(n) => { + if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) { + return Err(HostError::Range(format!("{what} must be a whole number from {lo} to {hi}"))); + } + } + _ => return Err(HostError::Type(format!("{what} must be a number"))), + }, + Kind::Text => match d { + Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))), + Data::String(_) => {} + _ => return Err(HostError::Type(format!("{what} must be a string"))), + }, + Kind::Choice(e, all, ok) => { + let bad = || HostError::Type(format!("{what} must be a {e} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(e).and_then(|r| r.strip_prefix('.')).filter(|m| all.contains(m)).ok_or_else(bad)?; + if !ok.contains(&m) { + return Err(HostError::Error(format!("{e}.{m} is not available yet"))); + } + } + Kind::Child(c) => { + let index = class_index(c).ok_or_else(|| HostError::Type(format!("{what} must be a {c}")))?; + slot_of(h, d, index).map_err(|e| match e { + HostError::Type(_) => HostError::Type(format!("{what} must be a {c}")), + e => e, + })?; + } + Kind::File => { + if vectorcraft_js::file_ref_path(d).is_none() { + return Err(HostError::Type(format!("{what} must be a File"))); + } + } + } + Ok(Some(d.clone())) +} + +fn read(h: &Host, class: usize, field: usize, this: &Data) -> Answer { + let slot = slot_of(h, this, class)?; + let spec = &CLASSES[class].fields[field]; + let stored = h.dom.printing.objects.borrow()[slot].set.iter().find(|(k, _)| *k == spec.name).map(|(_, v)| v.clone()); + if let Some(v) = stored { + return Ok(v); + } + match spec.kind { + Kind::Child(c) => { + let index = class_index(c).ok_or_else(|| HostError::Type(format!("no option class {c}")))?; + let child = create(h, index)?; + h.dom.printing.objects.borrow_mut()[slot].set.push((spec.name, child.clone())); + Ok(child) + } + kind => Ok(spec.start.value(kind)), + } +} + +fn write(h: &Host, class: usize, field: usize, this: &Data, d: &Data) -> Answer { + let slot = slot_of(h, this, class)?; + let c = &CLASSES[class]; + let spec = &c.fields[field]; + let value = checked(h, c, spec, d)?; + let mut objects = h.dom.printing.objects.borrow_mut(); + let set = &mut objects[slot].set; + set.retain(|(k, _)| *k != spec.name); + if let Some(v) = value { + set.push((spec.name, v)); + } + Ok(Data::Undefined) +} + +fn property(link: &Link, class: usize, field: usize) -> HostMember { + let (l, m) = (link.clone(), link.clone()); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + read(&h, class, field, arg(&a, 0)) + }); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&m)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write(&h, class, field, arg(&a, 0), arg(&a, 1)) + }); + HostMember::Property { get, set } +} + +// ---- Mapping to file.print ---- + +/// What a `PrintOptions` asks `file.print` for. +#[derive(Default)] +struct Job { + preset: Option, + file: Option, + /// The assigned `printerName`. + printer: Option, + level: Option, + /// The assigned `artboardRange`, checked whether or not it picks the artboards. + range: Option, + /// The assigned names [`check_names`] checks before they go into `settings`: the flattener + /// preset, the color profile and the paper. + flattener: Option, + profile: Option, + paper: Option, + /// A paper `width` or `height` above 0 is assigned. + paper_size: bool, + /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. + source: bool, + /// `printArea` is assigned: the artboards print even when the base settings ignore them. + print_area: bool, + /// The groups of `settings`: the top level and each nested object by its key. + top: Map, + groups: Vec<(&'static str, Map)>, +} + +impl Job { + fn group(&mut self, key: &'static str) -> &mut Map { + let i = match self.groups.iter().position(|(k, _)| *k == key) { + Some(i) => i, + None => { + self.groups.push((key, Map::new())); + self.groups.len() - 1 + } + }; + &mut self.groups[i].1 + } + + fn settings(&mut self) -> Map { + let mut s = std::mem::take(&mut self.top); + for (k, g) in self.groups.drain(..) { + if !g.is_empty() { + s.insert(k.into(), Value::Object(g)); + } + } + s + } +} + +/// The assigned properties of the option object in `slot`. +fn assigned(h: &Host, slot: usize) -> Vec<(&'static str, Data)> { + h.dom.printing.objects.borrow()[slot].set.clone() +} + +/// The member name of a checked enumerated value (`"PrintTiling.TILEFULLPAGES"` → `TILEFULLPAGES`). +fn member_of(d: &Data) -> &str { + match d { + Data::String(s) => s.rsplit_once('.').map_or("", |(_, m)| m), + _ => "", + } +} + +fn flag(d: &Data) -> bool { + matches!(d, Data::Bool(true)) +} + +fn number_of(d: &Data) -> f64 { + match d { + Data::Number(n) => *n, + _ => 0.0, + } +} + +fn string_of(d: &Data) -> String { + match d { + Data::String(s) => s.clone(), + _ => String::new(), + } +} + +/// The slot of the child a stored `Kind::Child` value names. +fn child_slot(h: &Host, d: &Data, class: &str) -> std::result::Result { + let index = class_index(class).ok_or_else(|| HostError::Type(format!("no option class {class}")))?; + slot_of(h, d, index) +} + +fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), HostError> { + for (k, v) in assigned(h, slot) { + match k { + "flattenerPreset" => job.flattener = Some(string_of(&v)), + "printPreset" => job.preset = Some(string_of(&v)), + "printerName" => job.printer = Some(string_of(&v)), + "jobOptions" => map_job(h, child_slot(h, &v, JOB.name)?, job), + "colorManagementOptions" => map_color(h, child_slot(h, &v, COLOR.name)?, job), + "colorSeparationOptions" => map_separation(h, child_slot(h, &v, SEPARATION.name)?, job), + "coordinateOptions" => map_coordinate(h, child_slot(h, &v, COORDINATE.name)?, job)?, + "flattenerOptions" => map_flattener(h, child_slot(h, &v, FLATTENER.name)?, job), + "fontOptions" => { + child_slot(h, &v, FONT.name)?; + } + "pageMarksOptions" => map_marks(h, child_slot(h, &v, MARKS.name)?, job), + "paperOptions" => map_paper(h, child_slot(h, &v, PAPER.name)?, job), + "postScriptOptions" => map_postscript(h, child_slot(h, &v, POSTSCRIPT.name)?, job), + _ => {} + } + } + Ok(()) +} + +fn map_job(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); + for (k, v) in &set { + let s = &mut job.top; + match *k { + "copies" => { + s.insert("copies".into(), json!(whole(number_of(v)).unwrap_or(1))); + } + "collate" => { + s.insert("collate".into(), json!(flag(v))); + } + "reversePages" => { + s.insert("reverse".into(), json!(flag(v))); + } + "designation" => { + let layers = match member_of(v) { + "ALLLAYERS" => "all", + "VISIBLELAYERS" => "visible", + _ => "visiblePrintable", + }; + s.insert("printLayers".into(), json!(layers)); + } + "printAllArtboards" if flag(v) => { + s.insert("artboards".into(), json!("all")); + } + "printAllArtboards" => match value("artboardRange").map(string_of).filter(|r| !r.trim().is_empty()) { + Some(range) => { + s.insert("artboards".into(), json!("range")); + s.insert("range".into(), json!(range)); + } + None => { + s.insert("artboards".into(), json!("all")); + } + }, + "printAsBitmap" => { + job.group("advanced").insert("printAsBitmap".into(), json!(flag(v))); + } + "file" => job.file = Some(v.clone()), + "artboardRange" => { + job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()); + // Without `printAllArtboards`, the range replaces the base range and the base + // settings still decide whether a range prints. + if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) { + s.insert("range".into(), json!(range)); + } + } + "printArea" => job.print_area = true, + _ => {} + } + } +} + +fn map_color(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE"); + job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); + job.source = source; + let g = job.group("color"); + for (k, v) in &set { + if *k == "intent" { + let intent = match member_of(v) { + "ABSOLUTECOLORIMETRIC" => "absoluteColorimetric", + "PERCEPTUALINTENT" => "perceptual", + "SATURATIONINTENT" => "saturation", + _ => "relativeColorimetric", + }; + g.insert("intent".into(), json!(intent)); + } + } + if source { + g.insert("profile".into(), json!("")); + } +} + +fn map_separation(h: &Host, slot: usize, job: &mut Job) { + let g = job.group("output"); + for (k, v) in assigned(h, slot) { + match k { + "colorSeparationMode" => { + g.insert("mode".into(), json!(if member_of(&v) == "HOSTBASEDSEPARATION" { "separations" } else { "composite" })); + } + "convertSpotColors" => { + g.insert("spotsToProcess".into(), json!(flag(&v))); + } + "overPrintBlack" => { + g.insert("overprintBlack".into(), json!(flag(&v))); + } + _ => {} + } + } +} + +fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), HostError> { + let set = assigned(h, slot); + let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); + let (hs, vs) = (value("horizontalScale").map(number_of), value("verticalScale").map(number_of)); + let tiling = value("tiling").map(|v| match member_of(v) { + "TILEFULLPAGES" => "tileFull", + "TILEIMAGEABLEAREAS" => "tileImageable", + _ => "none", + }); + let fit = value("fitToPage").map(flag); + // With Fit to Page on, the scale factors are not used, so only a job that uses them is limited. + if fit != Some(true) { + for (name, n) in [("horizontalScale", hs), ("verticalScale", vs)] { + if n.is_some_and(|n| n > MAX_PRINT_SCALE) { + return Err(HostError::Error(format!("PrintCoordinateOptions.{name} above {MAX_PRINT_SCALE} is not available yet"))); + } + } + } + let scaled = hs.is_some() || vs.is_some(); + let scaling = if fit == Some(true) { + Some("fit") + } else if let Some(t) = tiling.filter(|t| *t != "none") { + Some(t) + } else if scaled { + Some("custom") + } else if fit.is_some() || tiling.is_some() { + Some("none") + } else { + None + }; + if let Some(scaling) = scaling { + job.top.insert("scaling".into(), json!(scaling)); + } + if scaled && fit != Some(true) { + // Only the assigned factors are sent; with one of them, the other keeps its value in the + // base settings (the preset's or the saved ones). + let g = job.group("scale"); + if let Some(w) = hs { + g.insert("width".into(), json!(w)); + } + if let Some(hh) = vs { + g.insert("height".into(), json!(hh)); + } + // Linked only when the factors are equal, as `file.print` compares them. + let linked = matches!((hs, vs), (Some(w), Some(hh)) if w == hh); + g.insert("linked".into(), json!(linked)); + } + for (k, v) in &set { + match *k { + "emulsion" => { + job.group("output").insert("emulsion".into(), json!(if flag(v) { "down" } else { "up" })); + } + "orientation" => { + let orientation = match member_of(v) { + "AUTOROTATE" => None, + "LANDSCAPE" => Some("landscape"), + "REVERSEPORTRAIT" => Some("portraitFlipped"), + "REVERSELANDSCAPE" => Some("landscapeFlipped"), + _ => Some("portrait"), + }; + job.top.insert("autoRotate".into(), json!(orientation.is_none())); + if let Some(o) = orientation { + job.top.insert("orientation".into(), json!(o)); + } + } + "position" => { + let origin = match member_of(v) { + "TRANSLATEBOTTOM" => "bottom", + "TRANSLATEBOTTOMLEFT" => "bottomLeft", + "TRANSLATEBOTTOMRIGHT" => "bottomRight", + "TRANSLATELEFT" => "left", + "TRANSLATERIGHT" => "right", + "TRANSLATETOP" => "top", + "TRANSLATETOPLEFT" => "topLeft", + "TRANSLATETOPRIGHT" => "topRight", + _ => "center", + }; + job.group("placement").insert("origin".into(), json!(origin)); + } + _ => {} + } + } + Ok(()) +} + +fn map_flattener(h: &Host, slot: usize, job: &mut Job) { + for (k, v) in assigned(h, slot) { + if k == "overprint" { + let keep = member_of(&v) == "PRESERVEPDFOVERPRINT"; + job.group("advanced").insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); + } + } +} + +fn map_marks(h: &Host, slot: usize, job: &mut Job) { + let g = job.group("marks"); + for (k, v) in assigned(h, slot) { + let (key, value) = match k { + "colorBars" => ("colorBars", json!(flag(&v))), + "pageInfoMarks" => ("pageInfo", json!(flag(&v))), + "registrationMarks" => ("registration", json!(flag(&v))), + "trimMarks" => ("trim", json!(flag(&v))), + "pageMarksType" => ("kind", json!(if member_of(&v) == "Japanese" { "japanese" } else { "roman" })), + "trimMarksWeight" => ("weight", json!(number_of(&v))), + _ => continue, + }; + g.insert(key.into(), value); + } +} + +fn map_paper(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let size = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| number_of(v)).filter(|n| *n > 0.0); + let (width, height) = (size("width"), size("height")); + job.paper = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); + job.paper_size = width.is_some() || height.is_some(); + let s = &mut job.top; + if job.paper.is_none() && (width.is_some() || height.is_some()) { + s.insert("media".into(), json!("custom")); + } + if let Some(w) = width { + s.insert("width".into(), json!(w)); + } + if let Some(hh) = height { + s.insert("height".into(), json!(hh)); + } + if let Some((_, v)) = set.iter().find(|(k, _)| *k == "transverse") { + s.insert("transverse".into(), json!(flag(v))); + } +} + +fn map_postscript(h: &Host, slot: usize, job: &mut Job) { + for (k, v) in assigned(h, slot) { + match k { + "negativePrinting" => { + job.group("output").insert("image".into(), json!(if flag(&v) { "negative" } else { "positive" })); + } + "postScriptLevel" => job.level = Some(if member_of(&v) == "PSLEVEL2" { 2 } else { 3 }), + _ => {} + } + } +} + +/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names, +/// with the assigned options over the document's print settings, or without a file the job for a +/// printer ([`prepare`]). +fn doc_print(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let mut job = Job::default(); + if let Some(o) = given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + let slot = slot_of(h, o, 0).map_err(|e| match e { + HostError::Type(_) => HostError::Type("print's options must be a PrintOptions object".into()), + e => e, + })?; + map_options(h, slot, &mut job)?; + } + let Some(file) = job.file.take() else { return prepare(h, doc, job) }; + check_names(h, doc, &mut job)?; + let path = file_path(&file, "print")?; + let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + let mut p = print_params(&mut job); + // The format follows the name `jobOptions.file` gives, not the real path a link leads to. + let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps"; + p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); + p.insert("path".into(), json!(plain(real)?)); + let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?; + // What the job lost or how its options apply: one Script Console line each. + let warnings = match &printed { + Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v), + _ => None, + }; + if let Some(Data::Array(warnings)) = warnings { + for w in warnings.iter().take(MAX_LISTED) { + if let Data::String(w) = w { + console_warning(h, w); + } + } + } + Ok(Data::Undefined) +} + +/// Writes `file.print`'s warning `w` to the Script Console. +fn console_warning(h: &Host, w: &str) { + super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut)); +} + +/// `file.print`'s params for `job`, without a path: the print preset, the PostScript level and the +/// settings. +fn print_params(job: &mut Job) -> Map { + let mut p = Map::new(); + if let Some(preset) = job.preset.take() { + p.insert("preset".into(), json!(preset)); + } + if let Some(level) = job.level { + p.insert("level".into(), json!(level)); + } + let settings = job.settings(); + if !settings.is_empty() { + p.insert("settings".into(), Value::Object(settings)); + } + p +} + +/// `document.print(options?)` without `jobOptions.file`: the job for the printer `printerName` +/// names, or for the system's default printer, as `file.print` composes it now. The run keeps it, +/// and the session takes it only when the run's changes are kept ([`super::super::printing`]). +/// Everything is checked before the job is composed, and its size after. +fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { + let state = &h.dom.printing; + let (printer, for_printer) = { + let printers = state.printers.borrow(); + let Some(printers) = printers.as_ref() else { return Err(HostError::Error(NO_PRINTER.into())) }; + let printer = match job.printer.take().filter(|n| !n.is_empty()) { + Some(name) if printers.has(&name) => name, + Some(name) => return Err(HostError::Error(format!("PrintOptions.printerName names no installed printer: {name}"))), + None => printers.default_name().map(str::to_string).ok_or_else(|| HostError::Error(NO_DEFAULT_PRINTER.into()))?, + }; + (printer, printers.for_printer) + }; + if state.waiting.get() { + return Err(HostError::Error(PRINT_WAITING.into())); + } + if job.level.is_some() { + return Err(HostError::Error(POSTSCRIPT_TO_FILE.into())); + } + let (count, sheets, bytes) = { + let jobs = state.jobs.borrow(); + (jobs.len(), jobs.iter().map(|j| j.sheets).sum::(), jobs.iter().map(|j| j.pdf.len()).sum::()) + }; + if count >= MAX_JOBS { + return Err(HostError::Range(format!("a script can print at most {MAX_JOBS} jobs to a printer in a run"))); + } + check_names(h, doc, &mut job)?; + let mut p = print_params(&mut job); + if for_printer { + p.insert("forPrinter".into(), json!(true)); + } + // `file.print` counts the pages of the art as it prints and composes the job only when they fit. + p.insert("maxPages".into(), json!(MAX_SHEETS.saturating_sub(sheets))); + let printed = on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command_kept(h, PRINT, &Value::Object(p))))?; + let pages = printed.get("pages").and_then(Value::as_u64).unwrap_or(0); + sheets_fit(sheets, pages)?; + let pdf = printed + .get("dataBase64") + .and_then(Value::as_str) + .and_then(vectorcraft_format::base64_decode) + .ok_or_else(|| HostError::Error("the print job has no data".into()))?; + if bytes.saturating_add(pdf.len()) > MAX_JOB_BYTES { + return Err(HostError::Range("a script's printer jobs can hold at most 32 MiB in a run".into())); + } + for w in printed.get("warnings").and_then(Value::as_array).into_iter().flatten().take(MAX_LISTED) { + if let Some(w) = w.as_str() { + console_warning(h, w); + } + } + let title = with_doc(h, doc, |_, st| st.title()); + state.jobs.borrow_mut().push(PreparedPrint { printer, title, pdf, sheets: pages }); + Ok(Data::Undefined) +} + +/// Checks, before anything is written, the artboard range against the document's artboards and +/// each assigned name against the list it must come from, and puts the checked names into the +/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its +/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or +/// a control character, throws. +fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { + let (count, saved_ignore) = with_doc(h, doc, |_, st| { + let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); + (st.doc.artboards.len(), mode == Some("ignore")) + }); + if let Some(range) = &job.range { + vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; + } + let s = h.session.borrow(); + let mut base_ignore = saved_ignore; + if let Some(name) = job.preset.take() { + let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; + let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?; + base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore); + job.preset = Some(n.to_string()); + } + // An assigned `printArea` prints by artboard when the base settings ignore the artboards: the + // assigned `artboardRange` when there is one, otherwise every artboard. + if job.print_area && base_ignore && !job.top.contains_key("artboards") { + let mode = if job.top.contains_key("range") { "range" } else { "all" }; + job.top.insert("artboards".into(), json!(mode)); + } + if let Some(name) = job.flattener.take() { + let n = plain_name("PrintOptions.flattenerPreset", "flattener preset", &name)?; + if FlattenOptions::find_preset(n, &s.prefs.flattener_presets).is_none() { + return Err(no_such("PrintOptions.flattenerPreset", "flattener preset", &name)); + } + job.group("advanced").insert("flattenerPreset".into(), json!(n)); + } + if let Some(name) = job.profile.take() { + let what = "PrintColorManagementOptions.name"; + let n = plain_name(what, "color profile", &name)?; + let n = cms::LEGACY_NAMES.iter().find(|(old, _)| old.eq_ignore_ascii_case(n)).map_or(n, |(_, new)| new); + let profile = cms::profiles() + .into_iter() + .find(|p| p.kind != cms::ProfileKind::Gray && p.name.eq_ignore_ascii_case(n)) + .ok_or_else(|| no_such(what, "color profile", &name))?; + if !job.source { + job.group("color").insert("profile".into(), json!(profile.name)); + } + } + if let Some(name) = job.paper.take() { + let n = plain_name("PrintPaperOptions.name", "paper", &name)?; + let media = vectorcraft_pdf::Media::from_name(n).ok_or_else(|| no_such("PrintPaperOptions.name", "paper", &name))?; + if job.paper_size && media != vectorcraft_pdf::Media::Custom { + return Err(HostError::Error(format!("PrintPaperOptions.width and height apply only to custom paper, not {name}"))); + } + job.top.insert("media".into(), json!(media.id())); + } + Ok(()) +} + +/// The error for a name that is not on its list. +fn no_such(what: &str, kind: &str, name: &str) -> HostError { + HostError::Error(format!("{what} names no {kind}: {name}")) +} + +/// `name` without the spaces around it, or an error when it is empty or holds a path separator or +/// a control character. +fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result<&'a str, HostError> { + // Control characters are looked for before the trim, which would drop a tab or a line break. + if name.chars().any(char::is_control) { + return Err(no_such(what, kind, name)); + } + let n = name.trim(); + if n.is_empty() { + return Err(HostError::Error(format!("{what} must name a {kind}"))); + } + if n.contains(['/', '\\']) { + return Err(no_such(what, kind, name)); + } + Ok(n) +} + +/// The error when a job of `pages` sheets would take a run's jobs past [`MAX_SHEETS`], after +/// `sheets` in earlier jobs. +fn sheets_fit(sheets: u64, pages: u64) -> std::result::Result<(), HostError> { + if sheets.saturating_add(pages) > MAX_SHEETS { + return Err(HostError::Range(format!("a script's printer jobs can hold at most {MAX_SHEETS} sheets in a run; this job has {pages}"))); + } + Ok(()) +} + +const PRINT: &str = "file.print"; + +/// Runs `run`, which runs `id`, a command scripts may not run through `vc.run`, for a member that +/// checked its params: only `id` passes the fence, and only while `run` runs. +fn unfenced(h: &Host, id: &'static str, run: impl FnOnce() -> std::result::Result) -> std::result::Result { + h.session.borrow_mut().script_unfenced = Some(id); + #[cfg(test)] + if crate::script::PANIC_WHILE_UNFENCED.with(std::cell::Cell::get) { + panic!("a command past the fence failed"); + } + let r = run(); + h.session.borrow_mut().script_unfenced = None; + r +} + +/// `app.printPresetsList`: the names of the print presets, `[Default]` first. +fn app_presets(h: &Host, _: &[Data]) -> Answer { + let presets = h.session.borrow().print_presets(); + Ok(Data::Array(presets.into_iter().take(MAX_LISTED).map(|p| text(p.name)).collect())) +} + +fn app_ppd_files(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Array(Vec::new())) +} + +/// `app.printerList`: a `Printer` for each printer the frontend listed for the run. +fn app_printers(h: &Host, _: &[Data]) -> Answer { + if h.session.borrow().active().is_none() { + return Err(HostError::Error(PRINTERS_NEED_DOCUMENT.into())); + } + let printers = h.dom.printing.printers.borrow(); + let printers = printers.as_ref().ok_or_else(|| HostError::Error(NO_PRINTERS.into()))?; + let count = u64::try_from(printers.names().len()).unwrap_or(0); + Ok(Data::Array((0..count).map(|i| host_ref(PRINTER, &[float(h.run), float(i)])).collect())) +} + +const PRINTER: &str = "Printer"; + +/// `printer.name`: the name the frontend listed for the printer. +fn printer_name(h: &Host, a: &[Data]) -> Answer { + let wrong = || HostError::Type("this is not a Printer".into()); + let (class, handle) = host_ref_parts(arg(a, 0)).ok_or_else(wrong)?; + if class != PRINTER { + return Err(wrong()); + } + let [run, index] = handle.as_slice() else { return Err(wrong()) }; + let stale = || HostError::Error(STALE_PRINTER.into()); + if whole(*run) != Some(h.run) { + return Err(stale()); + } + let index = whole(*index).and_then(|i| usize::try_from(i).ok()).ok_or_else(stale)?; + let printers = h.dom.printing.printers.borrow(); + printers.as_ref().and_then(|p| p.names().get(index)).map(|n| text(n.clone())).ok_or_else(stale) +} + +/// The members these add to `Application`. +pub(super) fn application_members(l: &Link) -> Vec { + named(vec![ + ("printPresetsList", get(l, app_presets), MemberInfo { collection: true, ..typed("string") }), + ("PPDFileList", get(l, app_ppd_files), MemberInfo { collection: true, ..typed("PPDFile") }), + ("printerList", get(l, app_printers), MemberInfo { collection: true, ..typed(PRINTER) }), + ]) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![("print", method(l, doc_print), returns("undefined", &[("options", "PrintOptions")]))]) +} + +/// What `reflect` tells of an option field. +fn field_info(field: &Field) -> MemberInfo { + match field.kind { + Kind::Bool => typed("boolean"), + // A field with no upper limit, such as `bitmapResolution`, reports no maximum. + Kind::Number(min, max) => MemberInfo { min: Some(min), max: (max < f64::MAX).then_some(max), ..typed("number") }, + #[allow(clippy::cast_precision_loss)] + Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") }, + Kind::Text => typed("string"), + Kind::Choice(name, _, _) | Kind::Child(name) => typed(name), + Kind::File => typed("File"), + } +} + +/// The option classes: each `new Name()` gives a new option object with nothing assigned. And +/// `Printer`, whose objects only `app.printerList` gives. +pub(super) fn classes(link: &Link) -> Vec { + let mut classes: Vec = CLASSES + .iter() + .enumerate() + .map(|(index, c)| { + let l = link.clone(); + let construct: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + create(&h, index) + }); + let mut members = vec![("typename".to_string(), super::typename_of(c.name), typed("string"))]; + members.extend(c.fields.iter().enumerate().map(|(i, field)| (field.name.to_string(), property(link, index, i), field_info(field)))); + HostClass { construct: Some(construct), ..class(c.name, None, members, None) } + }) + .collect(); + let mut printer = named(vec![("typename", super::typename_of(PRINTER), typed("string")), ("name", get(link, printer_name), typed("string"))]); + printer.push(later(link, PRINTER, "printerInfo")); + classes.push(class(PRINTER, None, printer, None)); + classes +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs new file mode 100644 index 0000000000..fd933f7d60 --- /dev/null +++ b/crates/engine/src/script/dom/save_open.rs @@ -0,0 +1,1140 @@ +//! Saving, exporting and opening documents in the script object model: `Document.saveAs`, +//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`, +//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the +//! help pages , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's +//! transaction. The file is a `File` object, and the method reads and writes only where that +//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the +//! command's own reads and writes leave out the files of the open documents that `vc.run`'s +//! commands may use. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `saveAs` without options saves in the format the path's extension names; it writes the file +//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. +//! `exportFile` adds the format's extension unless the name already ends +//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes +//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. +//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, +//! and when one of those files may not be written, none of them is. +//! - An option the classes here map is applied; a listed option that is not mapped is accepted at +//! the default its help page gives and throws an error that says it is not available yet at any +//! other value; a property the help pages do not list throws an error that names it, unless it is +//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default +//! keeps the preset's value. A `pDFPreset` in square brackets names the built-in preset of the +//! name inside them; the default preset's name and `[PDF/X-4:2008]` name VectorCraft Default and +//! PDF/X-4:2010. +//! - `artboardRange` is a string, or a number read as `String(number)`. With +//! `saveMultipleArtboards` true, a `.ai` save also writes each artboard of the range (all when it +//! is empty) to a file of its own, `-.ai`. An EPS save of a range of two or +//! more artboards writes the file at the path and `_.eps` for each of them, and an EPS +//! save of one artboard writes only the file at the path, holding that artboard. Without +//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of +//! artboard numbers throws. +//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no +//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! `fullName` and `path` of a document whose file the automation read roots do not allow throw +//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`. +//! Assigning its current value runs no command. +//! - `Document.close` with unsaved changes closes without them with +//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with +//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or +//! recovered one included). `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws, since a +//! script cannot show the prompt. +//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property +//! but `typename` and `parent` throws the same error, unless it is `undefined`. +//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files. +//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte. +//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error. +//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The +//! commands a script runs never show a dialog, so the level does not change what they do, and it +//! never allows a file the script's grants do not. + +use std::cell::Cell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; + +use super::{ + Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named, + num, on_doc, property, returns, text, this_doc, typed, whole, +}; + +/// The most a scale factor of an export takes, in percent. +pub const MAX_SCALE_PERCENT: f64 = 776.19; +/// The least a scale factor of a raster export takes, in percent: `document.export` writes at least +/// 0.01 pixels per point. +pub const MIN_SCALE_PERCENT: f64 = 1.0; + +/// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`. +#[derive(Default)] +pub(in crate::script) struct State { + quiet: Cell, +} + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ( + "Compatibility", + &[ + "ILLUSTRATOR8", + "ILLUSTRATOR9", + "ILLUSTRATOR10", + "ILLUSTRATOR11", + "ILLUSTRATOR12", + "ILLUSTRATOR13", + "ILLUSTRATOR14", + "ILLUSTRATOR15", + "ILLUSTRATOR16", + "ILLUSTRATOR17", + "ILLUSTRATOR19", + "JAPANESEVERSION3", + ], + ), + ("PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"]), + ("PDFBoxType", &["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]), + ("EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"]), + ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), + ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), + ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + ("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]), + // The enumerations of the options that keep their defaults (`Default::Member`). + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "None", + "ZIP4BIT", + "ZIP8BIT", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]), + ("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]), +]; + +const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; +const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; + +/// The default a listed option that is not mapped keeps: a value equal to it is accepted. +#[derive(Clone, Copy)] +enum Default { + Bool(bool), + Num(f64), + Text(&'static str), + /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for + /// `DownsampleMethod.NODOWNSAMPLE`). + Member(&'static str, &'static str), + /// The help page gives no default: any value throws. + Unset, +} + +impl Default { + fn matches(self, d: &Data) -> bool { + match (self, d) { + (Default::Bool(a), Data::Bool(b)) => a == *b, + (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Default::Text(a), Data::String(b)) => a == b, + (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + _ => false, + } + } +} + +/// A mapped option: from its name and value into the command's params, `Ok(false)` for a name it +/// does not map. +type Mapper = fn(&str, &Data, &mut Map) -> std::result::Result; + +/// An option class: its name, its mapped options, its listed options that are not mapped, and the +/// defaults a new object starts with. +struct OptionClass { + name: &'static str, + map: Mapper, + kept: &'static [(&'static str, Default)], + starts: fn() -> Vec<(&'static str, Data)>, +} + +fn not_available(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class}.{name} is not available yet")) +} + +/// The error a property that the help page of `class` does not list throws. +fn not_an_option(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class} has no option {name}")) +} + +fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result { + match d { + Data::Number(n) => { + whole(*n).filter(|n| (lo..=hi).contains(n)).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from {lo} to {hi}"))) + } + _ => Err(HostError::Type(format!("{what} must be a number"))), + } +} + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`), one of `members`. +fn member<'a>(d: &'a Data, enumeration: &str, members: &[&str], what: &str) -> std::result::Result<&'a str, HostError> { + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A `Compatibility` value: the versions from 17 on are the file VectorCraft writes; older ones are +/// not available. +fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> { + let all = ENUMS.iter().find(|(n, _)| *n == "Compatibility").map_or(&[][..], |(_, m)| *m); + match member(d, "Compatibility", all, &format!("{class}.compatibility"))? { + "ILLUSTRATOR17" | "ILLUSTRATOR19" => Ok(()), + _ => Err(not_available(class, "compatibility")), + } +} + +/// An artboard range: a string, or a whole number from 1 read as `String(number)` reads it, given to +/// the command as `range` unless it is empty. Any other number throws. +fn range(d: &Data, what: &str, p: &mut Map) -> std::result::Result<(), HostError> { + let s = match d { + Data::String(s) => s.clone(), + Data::Number(n) => { + whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?; + vectorcraft_js::number_to_string(*n) + } + _ => return Err(HostError::Type(format!("{what} must be a string or a number"))), + }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + if !s.trim().is_empty() { + p.insert("range".into(), json!(s)); + } + Ok(()) +} + +// ---- Save options ---- + +fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("IllustratorSaveOptions.{name}"); + match name { + "compressed" => p.insert("compress".into(), json!(boolean(d, &what)?)), + "pdfCompatible" => p.insert("pdfCompatible".into(), json!(boolean(d, &what)?)), + "embedICCProfile" => p.insert("embedProfiles".into(), json!(boolean(d, &what)?)), + "compatibility" => { + compatibility("IllustratorSaveOptions", d)?; + None + } + "artboardRange" | "saveMultipleArtboards" => return artboards_map("IllustratorSaveOptions", name, d, p), + _ => return Ok(false), + }; + Ok(true) +} + +/// `artboardRange` and `saveMultipleArtboards` of a `.ai` or EPS save, as `range` and +/// [`MULTIPLE`] until [`artboard_files`] reads them together. +fn artboards_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + if name == "artboardRange" { + range(d, &what, p)?; + } else { + p.insert(MULTIPLE.into(), json!(boolean(d, &what)?)); + } + Ok(true) +} + +/// The key [`artboards_map`] keeps `saveMultipleArtboards` under. +const MULTIPLE: &str = "_multiple"; + +/// The params of a `.ai` (`format` `ai`) or EPS save for `saveMultipleArtboards` and +/// `artboardRange`: with `saveMultipleArtboards` true, the range (all when it is empty) goes to +/// `separateArtboards` of a `.ai` save or `useArtboards` of an EPS save, which write the artboards' +/// files; otherwise the range is not used, as the help pages say, but one that is not written as a +/// range ([`written_as_range`]) still throws. +fn artboard_files(format: &str, q: &mut Map) -> std::result::Result<(), HostError> { + let multiple = q.remove(MULTIPLE).and_then(|v| v.as_bool()).unwrap_or(false); + if !multiple { + if let Some(Value::String(r)) = q.remove("range") + && !r.trim().eq_ignore_ascii_case("all") + && !written_as_range(&r) + { + return Err(HostError::Range(format!("artboardRange `{r}` is not a range of artboard numbers"))); + } + } else if format == "ai" { + q.insert("separateArtboards".into(), json!(true)); + } else { + q.insert("useArtboards".into(), json!(true)); + } + Ok(()) +} + +/// Whether `r` is written as an artboard range, whatever artboards a document has: one or more +/// parts separated by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out +/// and the first no greater than the second. +fn written_as_range(r: &str) -> bool { + // A number of digits alone, from 1; past `u64` it counts as the largest. + let num = |t: &str| -> Option> { + let t = t.trim(); + if t.is_empty() { + return Some(None); + } + let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::().unwrap_or(u64::MAX))?; + (n >= 1).then_some(Some(n)) + }; + let mut parts = r.split(',').map(str::trim).filter(|p| !p.is_empty()).peekable(); + parts.peek().is_some() + && parts.all(|part| match part.replace('\u{2013}', "-").split_once('-') { + Some((a, b)) => match (num(a), num(b)) { + (Some(Some(a)), Some(Some(b))) => a <= b, + (Some(a), Some(b)) => a.is_some() || b.is_some(), + _ => false, + }, + None => matches!(num(part), Some(Some(_))), + }) +} + +const AI_KEPT: &[(&str, Default)] = &[ + ("embedLinkedFiles", Default::Bool(false)), + ("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")), + ("fontSubsetThreshold", Default::Num(100.0)), +]; + +fn ai_starts() -> Vec<(&'static str, Data)> { + vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] +} + +fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("EPSSaveOptions.{name}"); + match name { + "cmykPostScript" => { + p.insert("cmykPostScript".into(), json!(boolean(d, &what)?)); + } + "includeDocumentThumbnails" => { + p.insert("thumbnails".into(), json!(boolean(d, &what)?)); + } + "postScript" => { + let level = if member(d, "EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"], &what)? == "LEVEL2" { 2 } else { 3 }; + p.insert("level".into(), json!(level)); + } + "preview" => { + let (format, transparent) = match member(d, "EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"], &what)? { + "BWTIFF" => ("tiffBw", None), + "COLORTIFF" => ("tiffColor", Some(false)), + "TRANSPARENTCOLORTIFF" => ("tiffColor", Some(true)), + _ => ("none", None), + }; + p.insert("previewFormat".into(), json!(format)); + if let Some(t) = transparent { + p.insert("transparentPreview".into(), json!(t)); + } + } + "overprint" => { + let keep = member(d, "PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"], &what)? == "PRESERVEPDFOVERPRINT"; + p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); + } + "compatibility" => compatibility("EPSSaveOptions", d)?, + "artboardRange" | "saveMultipleArtboards" => return artboards_map("EPSSaveOptions", name, d, p), + _ => return Ok(false), + } + Ok(true) +} + +const EPS_KEPT: &[(&str, Default)] = &[ + ("compatibleGradientPrinting", Default::Bool(false)), + ("embedAllFonts", Default::Bool(false)), + ("embedLinkedFiles", Default::Unset), + ("flattenOuput", Default::Unset), +]; + +fn eps_starts() -> Vec<(&'static str, Data)> { + vec![("postScript", text("EPSPostScriptLevelEnum.LEVEL2")), ("overprint", text("PDFOverprint.PRESERVEPDFOVERPRINT"))] +} + +fn pdf_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("PDFSaveOptions.{name}"); + match name { + "pDFPreset" => { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + p.insert("preset".into(), json!(s)); + } + "compatibility" => { + let version = match member(d, "PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"], &what)? { + "ACROBAT4" => "1.3", + "ACROBAT5" => "1.4", + "ACROBAT6" => "1.5", + "ACROBAT7" => "1.6", + _ => "1.7", + }; + p.insert("compatibility".into(), json!(version)); + } + "artboardRange" => range(d, &what, p)?, + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "acrobatLayers" => { + p.insert("createLayers".into(), json!(boolean(d, &what)?)); + } + "compressArt" => { + p.insert("compression".into(), json!({"compressText": boolean(d, &what)?})); + } + _ => return Ok(false), + } + Ok(true) +} + +const PDF_KEPT: &[(&str, Default)] = &[ + ("bleedLink", Default::Bool(true)), + ("bleedOffsetRect", Default::Unset), + ("colorBars", Default::Bool(false)), + ("colorCompression", Default::Member("CompressionQuality", "None")), + ("colorConversionID", Default::Member("ColorConversion", "None")), + ("colorDestinationID", Default::Member("ColorDestination", "None")), + ("colorDownsampling", Default::Num(150.0)), + ("colorDownsamplingImageThreshold", Default::Num(225.0)), + ("colorDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("colorProfileID", Default::Member("ColorProfile", "None")), + ("colorTileSize", Default::Num(256.0)), + ("documentPassword", Default::Text("")), + ("enableAccess", Default::Bool(true)), + ("enableCopy", Default::Bool(true)), + ("enableCopyAccess", Default::Bool(true)), + ("enablePlainText", Default::Bool(false)), + ("flattenerOptions", Default::Unset), + ("flattenerPreset", Default::Unset), + ("fontSubsetThreshold", Default::Num(100.0)), + ("generateThumbnails", Default::Bool(true)), + ("grayscaleCompression", Default::Member("CompressionQuality", "None")), + ("grayscaleDownsampling", Default::Num(150.0)), + ("grayscaleDownsamplingImageThreshold", Default::Num(225.0)), + ("grayscaleDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("grayscaleTileSize", Default::Num(256.0)), + ("monochromeCompression", Default::Member("MonochromeCompression", "None")), + ("monochromeDownsampling", Default::Num(300.0)), + ("monochromeDownsamplingImageThreshold", Default::Num(450.0)), + ("monochromeDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("offset", Default::Num(0.0)), + ("optimization", Default::Bool(false)), + ("outputCondition", Default::Unset), + ("outputConditionID", Default::Unset), + ("pageInformation", Default::Bool(false)), + ("pageMarksType", Default::Member("PageMarksTypes", "Roman")), + ("pDFAllowPrinting", Default::Member("PDFPrintAllowedEnum", "PRINT128HIGHRESOLUTION")), + ("pDFChangesAllowed", Default::Member("PDFChangesAllowedEnum", "CHANGE128ANYCHANGES")), + ("pDFXStandard", Default::Member("PDFXStandard", "PDFXNONE")), + ("pDFXStandardDescription", Default::Unset), + ("permissionPassword", Default::Text("")), + ("printerResolution", Default::Num(800.0)), + ("registrationMarks", Default::Bool(false)), + ("requireDocumentPassword", Default::Bool(false)), + ("requirePermissionPassword", Default::Bool(false)), + ("trapped", Default::Bool(false)), + ("trimMarks", Default::Bool(false)), + ("trimMarkWeight", Default::Member("PDFTrimMarkWeight", "TRIMMARKWEIGHT0125")), + ("viewAfterSaving", Default::Bool(false)), +]; + +fn pdf_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compatibility", text("PDFCompatibility.ACROBAT5")), + ("artboardRange", text("")), + ("preserveEditability", Data::Bool(true)), + ("acrobatLayers", Data::Bool(false)), + ("compressArt", Data::Bool(true)), + ] +} + +const SAVE_CLASSES: &[(OptionClass, &str)] = &[ + (OptionClass { name: "IllustratorSaveOptions", map: ai_map, kept: AI_KEPT, starts: ai_starts }, "ai"), + (OptionClass { name: "EPSSaveOptions", map: eps_map, kept: EPS_KEPT, starts: eps_starts }, "eps"), + (OptionClass { name: "PDFSaveOptions", map: pdf_map, kept: PDF_KEPT, starts: pdf_starts }, "pdf"), +]; + +// ---- Export options ---- + +/// The raster options PNG24 and JPEG share: anti-aliasing, the clip to the artboard and the scale. +fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + match name { + "antiAliasing" => { + p.insert("antiAlias".into(), json!(if boolean(d, &what)? { "art" } else { "none" })); + } + "artBoardClipping" => { + p.insert("_clip".into(), json!(boolean(d, &what)?)); + } + "horizontalScale" | "verticalScale" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(MIN_SCALE_PERCENT..=MAX_SCALE_PERCENT).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 1 and at most 776.19"))); + } + let key = if name == "horizontalScale" { "_h" } else { "_v" }; + p.insert(key.into(), json!(n)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + if name == "transparency" { + let clear = boolean(d, "ExportOptionsPNG24.transparency")?; + p.insert("background".into(), json!(if clear { "transparent" } else { "white" })); + return Ok(true); + } + raster_map("ExportOptionsPNG24", name, d, p) +} + +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn png24_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("artBoardClipping", Data::Bool(false)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("transparency", Data::Bool(true)), + ] +} + +fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + match name { + "qualitySetting" => { + p.insert("quality".into(), json!(whole_in(d, "ExportOptionsJPEG.qualitySetting", 0, 100)?)); + Ok(true) + } + "optimization" => { + let optimized = boolean(d, "ExportOptionsJPEG.optimization")?; + p.insert("method".into(), json!(if optimized { "optimized" } else { "baseline" })); + Ok(true) + } + _ => raster_map("ExportOptionsJPEG", name, d, p), + } +} + +const JPEG_KEPT: &[(&str, Default)] = + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn jpeg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("optimization", Data::Bool(true)), + ("qualitySetting", num(30.0)), + ] +} + +fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsSVG.{name}"); + match name { + "coordinatePrecision" => { + p.insert("decimals".into(), json!(whole_in(d, &what, 1, 7)?)); + } + "embedRasterImages" => { + p.insert("images".into(), json!(if boolean(d, &what)? { "embed" } else { "link" })); + } + "compressed" => { + p.insert("_svgz".into(), json!(boolean(d, &what)?)); + } + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "includeVariablesAndDatasets" => { + p.insert("variableData".into(), json!(boolean(d, &what)?)); + } + _ => return Ok(false), + } + Ok(true) +} + +const SVG_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")), + ("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")), + ("DTD", Default::Member("SVGDTDVersion", "SVG1_1")), + ("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")), + ("fontType", Default::Member("SVGFontType", "CEFFONT")), + ("includeFileInfo", Default::Bool(false)), + ("includeUnusedStyles", Default::Bool(false)), + ("optimizeForSVGViewer", Default::Bool(false)), + ("saveMultipleArtboards", Default::Bool(false)), + ("slices", Default::Bool(false)), + ("sVGAutoKerning", Default::Bool(false)), + ("sVGTextOnPath", Default::Bool(false)), +]; + +fn svg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compressed", Data::Bool(false)), + ("coordinatePrecision", num(3.0)), + ("embedRasterImages", Data::Bool(false)), + ("includeVariablesAndDatasets", Data::Bool(false)), + ("preserveEditability", Data::Bool(false)), + ] +} + +const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; +const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; +const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; + +/// An `ExportType`: the format `document.export` writes, the extensions a file name may already +/// end with (the first is added), and its option class (`None`: no options are taken). +struct ExportKind { + format: &'static str, + extensions: &'static [&'static str], + options: Option<&'static OptionClass>, +} + +fn export_kind(d: &Data) -> std::result::Result { + let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); + let raster = |format, extensions| ExportKind { format, extensions, options: None }; + Ok(match member(d, "ExportType", all, "exportType")? { + "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, + "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, + "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, + "PNG8" => raster("png8", &["png"]), + "GIF" => raster("gif", &["gif"]), + "TIFF" => raster("tiff", &["tif", "tiff"]), + other => return Err(HostError::Error(format!("ExportType.{other} is not available yet"))), + }) +} + +/// The command's params for the options object `d` of `class`, read as the module's rules say. +fn options_params(class: &OptionClass, d: &Data) -> std::result::Result, HostError> { + let wrong = || HostError::Type(format!("the options must be an {} object", class.name)); + let Data::Object(items) = d else { return Err(wrong()) }; + if !items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class.name)) { + return Err(wrong()); + } + // With a PDF preset named, an option still at a new object's default leaves the preset's value. + let preset = class.name == "PDFSaveOptions" && items.iter().any(|(k, v)| k == "pDFPreset" && matches!(v, Data::String(s) if !s.is_empty())); + let starts = if preset { (class.starts)() } else { Vec::new() }; + let mut p = Map::new(); + for (k, v) in items { + if k == "typename" || matches!(v, Data::Undefined) || starts.iter().any(|(n, s)| n == k && s == v) { + continue; + } + if (class.map)(k, v, &mut p)? { + continue; + } + match class.kept.iter().find(|(n, _)| n == k) { + Some((_, default)) if default.matches(v) => {} + Some(_) => return Err(not_available(class.name, k)), + None => return Err(not_an_option(class.name, k)), + } + } + Ok(p) +} + +/// What `new Name()` gives for `class`: its `typename` and the defaults its help page gives for the +/// options mapped here. +fn fresh(class: &OptionClass) -> Data { + let mut items = vec![("typename".to_string(), text(class.name))]; + items.extend((class.starts)().into_iter().map(|(k, v)| (k.to_string(), v))); + Data::Object(items) +} + +/// The typename of an options object, when it has one. +fn typename(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("typename", Data::String(s)) => Some(s.as_str()), + _ => None, + }) +} + +// ---- Files ---- + +/// The path of the `File` argument `d`, or a `TypeError` naming the method. +pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> { + vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File"))) +} + +/// The error a refused path throws: the `File` error and the path. +pub(super) fn refused(message: &str, path: &str) -> HostError { + HostError::Error(format!("{message}: {path}")) +} + +/// Runs `f` with the commands' reads and writes held to the script's own grants +/// ([`super::super::files::Disk::exact`]). +pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { + h.disk.borrow_mut().exact = true; + let r = f(); + h.disk.borrow_mut().exact = false; + r +} + +/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s +/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or +/// a linked image an open could not read. → the command's answer. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (answer, value) = super::super::command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(answer) +} + +/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8. +pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result { + crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) +} + +/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the +/// preset each one names here (`Default` is VectorCraft's default preset, as +/// [`vectorcraft_pdf::builtin_preset`] reads it). +const PRESET_ALIASES: &[(&str, &str)] = &[ + ("Illustrator Default", "Default"), // brand-ok: the preset name scripts use + ("PDF/X-4:2008", "PDF/X-4:2010"), +]; + +/// A `pDFPreset` in square brackets (`[Smallest File Size]`) names the built-in preset of the name +/// inside the brackets, or the one [`PRESET_ALIASES`] gives for it. A preset the name already +/// names, a saved preset called `[Name]` included, is left as it is, and any other name is left for +/// the save to refuse. +fn builtin_preset_name(h: &Host, q: &mut Map) { + let Some(name) = q.get("preset").and_then(Value::as_str) else { return }; + let s = h.session.borrow(); + if crate::cmd::fileio::pdf::find_preset(name, &s.prefs.pdf_presets).is_some() { + return; + } + let Some(inside) = name.trim().strip_prefix('[').and_then(|n| n.strip_suffix(']')) else { return }; + let inside = PRESET_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(inside.trim())).map_or(inside, |(_, to)| to); + let Some(builtin) = vectorcraft_pdf::builtin_preset(inside, vectorcraft_pdf::APP) else { return }; + q.insert("preset".into(), json!(builtin.name)); +} + +/// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' +/// class names (`ai`, `eps`, `pdf`), or without options in the format of the path's extension. +fn doc_save_as(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "saveAs")?; + let mut p = Map::new(); + let given_options = given(arg(a, 2)); + // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options + // object of that format's class holds. + let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); + let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c)); + if let Some(o) = given_options.or(by_extension.as_ref()) { + let name = typename(o); + let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { + return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into())); + }; + let mut q = options_params(class, o)?; + if *format == "pdf" { + builtin_preset_name(h, &mut q); + } else { + artboard_files(format, &mut q)?; + } + p.insert("format".into(), json!(format)); + if *format == "ai" { + p.extend(q); + } else if !q.is_empty() { + p.insert("options".into(), Value::Object(q)); + } + } else { + let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); + p.insert("format".into(), json!(format)); + } + let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(real)?)); + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `path` with the extension of `kind` added, unless its name already ends with one of them. +fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { + let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + match extensions.first() { + Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"), + _ => path.to_string(), + } +} + +/// `document.exportFile(file, exportType, options?)`: `document.export` of one file, which leaves +/// the document's path as it is. +fn doc_export_file(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "exportFile")?; + let kind = export_kind(arg(a, 2))?; + // Without options, an export takes the defaults a new options object of its class holds. + let mut p = match given(arg(a, 3)) { + None => match kind.options { + Some(class) => options_params(class, &fresh(class))?, + None => Map::new(), + }, + Some(o) => match kind.options { + Some(class) => options_params(class, o)?, + None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())), + None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), + }, + }; + let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); + let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); + let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); + if (hs - vs).abs() > 1e-9 { + return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); + } + // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. + if kind.format != "svg" { + p.insert("scale".into(), json!(hs / 100.0)); + } + let format = if svgz { "svgz" } else { kind.format }; + p.insert("format".into(), json!(format)); + if kind.format == "svg" { + p.insert("useArtboards".into(), json!(false)); + } else if clip { + let artboard = super::with_doc(h, doc, |_, st| super::active_artboard(st)); + p.insert("artboard".into(), json!(artboard)); + } else { + p.insert("useArtboards".into(), json!(false)); + } + let named = with_extension(path, &kind, svgz); + let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; + p.insert("path".into(), json!(plain(real)?)); + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `app.open(file, documentColorSpace?, options?)`: `document.open` of the file, which becomes +/// the active document. → the document. +fn app_open(h: &Host, a: &[Data]) -> Answer { + let path = file_path(arg(a, 1), "open")?; + let mut p = Map::new(); + if let Some(d) = given(arg(a, 2)) { + let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" }; + p.insert("colorMode".into(), json!(mode)); + } + if let Some(o) = given(arg(a, 3)) { + let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) }; + if typename(o).is_some_and(|t| t != "PDFFileOptions") { + return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); + } + for (k, v) in items { + if matches!(v, Data::Undefined) { + continue; + } + match k.as_str() { + "pageToOpen" => { + p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?)); + } + "pDFCropToBox" => { + let boxes = ["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]; + let crop = match member(v, "PDFBoxType", &boxes, "PDFFileOptions.pDFCropToBox")? { + "PDFARTBOX" => "art", + "PDFBLEEDBOX" => "bleed", + "PDFBOUNDINGBOX" => "bounding", + "PDFCROPBOX" => "crop", + "PDFMEDIABOX" => "media", + _ => "trim", + }; + p.insert("cropTo".into(), json!(crop)); + } + // The read-only members the help page lists. + "typename" | "parent" => {} + _ => return Err(not_an_option("PDFFileOptions", k)), + } + } + } + if p.contains_key("cropTo") { + p.insert("editingData".into(), json!(false)); + } + // The command opens the given path; a real path that is not valid UTF-8 is still refused. + let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + plain(real)?; + p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?)); + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; + let index = match &r { + Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + }), + _ => None, + }; + let s = h.session.borrow(); + let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +/// The document's file, `None` for a document that has none, or `Script file access denied` with +/// the document's name when the automation read roots do not allow the file to be named +/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { + let path = st.path.as_deref().map(absolute_file).transpose()?; + match path.as_deref() { + Some(p) if crate::file_access::check_read(p).is_err() => { + Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) + } + _ => Ok(path), + } +} + +fn absolute_file(path: &str) -> std::result::Result { + let path = std::path::Path::new(path); + if path.is_absolute() { + Ok(path.to_string_lossy().into_owned()) + } else { + let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?; + Ok(cwd.join(path).to_string_lossy().into_owned()) + } +} + +/// `document.fullName`: a `File` for the document's file, or, for a document that has none, a +/// `File` for its name in `Folder.current`. +fn doc_full_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + super::with_doc(h, doc, |_, st| { + Ok(match shown_file(st)? { + Some(p) => vectorcraft_js::file_ref(&p), + None => vectorcraft_js::file_ref(&st.title()), + }) + }) +} + +/// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a +/// document that has none. +fn doc_path(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let folder = super::with_doc(h, doc, |_, st| { + Ok(shown_file(st)?.and_then(|p| { + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); + (!parent.is_empty()).then_some(parent) + })) + })?; + Ok(folder.map_or_else(|| text(""), |f| vectorcraft_js::folder_ref(&f))) +} + +/// `document.saved`: whether the document has no changes since it was opened or last saved. +fn doc_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(super::with_doc(h, doc, |_, st| !st.is_dirty()))) +} + +/// `document.saved = value`: `document.setSaved`, which records the document as saved or as having +/// unsaved changes without saving it. +fn doc_set_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let saved = boolean(arg(a, 1), "Document.saved")?; + if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) { + return Ok(Data::Undefined); + } + command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?; + Ok(Data::Undefined) +} + +/// The error `close` gives for a document with unsaved changes with +/// `SaveOptions.PROMPTTOSAVECHANGES`. +const UNSAVED_CHANGES: &str = + "the document has unsaved changes: save them first, or close with SaveOptions.SAVECHANGES or SaveOptions.DONOTSAVECHANGES"; + +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes that has +/// no file to save to. +const NO_FILE_TO_SAVE: &str = + "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose +/// save would keep only some of its artboards. +const SAVES_SOME_ARTBOARDS: &str = + "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// Whether the file that saving `st` with its remembered options writes would omit artboards. A +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` +/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its +/// `range` names only the separate files. An EPS file embeds the whole document in its main file, +/// so its `artboardRange` never omits an artboard from what reopens. +fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + if st.format == "eps" { + return false; + } + let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); + let svg = matches!(st.format, "svg" | "svgz"); + if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { + return true; + } + if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) { + return true; + } + let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options); + if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { + return false; + } + let count = st.doc.artboards.len(); + // A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is + // left for the save to refuse). + let modern_ai = matches!(st.format, "ai" | "ait") && !legacy; + let mut effective = options.clone(); + if let (true, Value::Object(o)) = (modern_ai, &mut effective) + && o.get("range").is_none_or(|r| r.is_string() || r.is_null()) + { + o.insert("range".into(), json!("all")); + } + let resolved = serde_json::from_value::(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count)); + // Such a `.ai` file, and an SVG file that carries the native document, keep every artboard; + // a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick). + if modern_ai { + return resolved.is_err(); + } + if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) { + return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err(); + } + match resolved { + Ok(None) => false, + Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)), + Err(_) => true, + } +} + +/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved +/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` +/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with +/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of +/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] +/// for a document that has no file, a converted or recovered one included, and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and +/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script +/// cannot show the prompt. +fn doc_close(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let how = match given(arg(a, 1)) { + Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, + None => "PROMPTTOSAVECHANGES", + }; + let (dirty, file, format, picked) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st))); + if dirty { + match how { + "DONOTSAVECHANGES" => {} + "SAVECHANGES" => { + let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?; + if picked { + return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); + } + // A refusal names the document, as `fullName` does when the read roots hide its file. + let name = super::with_doc(h, doc, |_, st| st.title()); + let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; + let p = json!({"path": plain(real)?, "format": format}); + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; + } + _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), + } + } + command(h, "file.close", &json!({"index": doc.index}))?; + Ok(Data::Undefined) +} + +fn app_interaction(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) +} + +fn app_set_interaction(h: &Host, a: &[Data]) -> Answer { + let quiet = member(arg(a, 1), "UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"], "userInteractionLevel")? == "DONTDISPLAYALERTS"; + h.dom.save_options.quiet.set(quiet); + Ok(Data::Undefined) +} + +/// The members these add to `Application`. +pub(super) fn application_members(l: &Link) -> Vec { + named(vec![ + ("open", method(l, app_open), returns("Document", &[("file", "File"), ("documentColorSpace", "DocumentColorSpace"), ("options", "*")])), + ("userInteractionLevel", property(l, app_interaction, app_set_interaction), typed("UserInteractionLevel")), + ]) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])), + ("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])), + ("fullName", get(l, doc_full_name), typed("File")), + ("path", get(l, doc_path), typed("Folder|string")), + ("saved", property(l, doc_saved, doc_set_saved), typed("boolean")), + ("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])), + ]) +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives for the options mapped here. +pub(super) fn classes(link: &Link) -> Vec { + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + all.map(|c| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + Ok(fresh(c)) + }); + HostClass { construct: Some(f), ..class(c.name, None, Vec::new(), None) } + }) + .collect() +} diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs index 294165b252..dff0120f78 100644 --- a/crates/engine/src/script/dom/tags.rs +++ b/crates/engine/src/script/dom/tags.rs @@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control Ok(()) }), Owner::Doc(doc) => with_doc(h, doc, |_, st| { - let ids = page_items(h, st); + let ids = page_items(h, st)?; h.charge_call(ids.len() as u64)?; for id in ids.iter() { if let Some(n) = st.doc.node(*id) { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 998652b81c..3c4acac317 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { } /// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the -/// document is unchanged. -fn frame_ids(h: &Host, st: &DocState) -> Rc> { +/// document is unchanged. Building the list again counts the page items it looks through against +/// the run's host-call allowance. +fn frame_ids(h: &Host, st: &DocState) -> std::result::Result>, HostError> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) { - return ids.clone(); + return Ok(ids.clone()); } - let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let all = page_items(h, st)?; + h.charge_call(all.len() as u64)?; + let ids: Vec = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); let ids = Rc::new(ids); *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); - ids + Ok(ids) } fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { @@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { fn frames_length(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { @@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) - }); + Ok::<_, HostError>((ids, refused, on_locked)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index e159893e8d..5ade055bc6 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result>, HostEr { return Ok(ids.clone()); } - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::())?; // A frame listed by an earlier thread belongs to that one, as `story_of` finds it. let (mut threaded, mut first) = (HashSet::new(), HashSet::new()); diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 86f150d3e6..1cded460ab 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -124,6 +124,8 @@ pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many step pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const READ_ONLY: &str = "Script file is read-only"; +pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; @@ -281,6 +283,9 @@ pub(crate) struct Disk { /// when they were last written to the grants file. kept: Vec<(std::path::PathBuf, bool, bool)>, recorded: usize, + /// While set, the gate of a command the script runs leaves out the files of the open documents + /// ([`Disk::gate`]): the command reads and writes only where the script's `File` objects may. + pub(crate) exact: bool, /// The write bits setting `readonly` cleared from each file in this run, by its device and /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. #[cfg(unix)] @@ -334,6 +339,7 @@ impl Disk { ran_too_much: setup.engine_code.1, kept: Vec::new(), recorded: 0, + exact: false, #[cfg(unix)] cleared: HashMap::new(), }; @@ -466,9 +472,12 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, the files the /// person gave the open documents, `documents`, and the files it may only read because the documents open when - /// the run began link to them, `linked`. + /// the run began link to them, `linked`, but not the files its `File` objects hold open for writing. pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } + // A save, export or open of a `File` the script names reads and writes as its `File` would. + let (documents, linked) = if self.exact { (Vec::new(), Default::default()) } else { (documents, linked) }; + let held = self.open.values().filter_map(|o| o.target.clone()).collect(); + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None } } /// The files written since this was last asked, to name in the report. @@ -687,6 +696,39 @@ impl Disk { } } + /// The real path a save or export of the document to `path` writes, as a `File` opened for + /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, a + /// read-only file is not written over, and neither is a file a `File` object holds open for + /// writing, whose bytes the run's end would write over the saved file. + pub(crate) fn save_target(&self, path: &str) -> Result { + let real = self.target(path, true)?; + if self.open.values().any(|o| o.target.as_deref() == Some(real.as_path())) { + return Err(OPEN_FOR_WRITING); + } + match std::fs::metadata(&real) { + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) if m.permissions().readonly() => Err(READ_ONLY), + _ => Ok(real), + } + } + + /// The real path of the file `path` that opening it as a document reads, as a `File` reads it + /// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or + /// the script may not read it. + pub(crate) fn open_target(&self, path: &str) -> Result { + let p = self.checked(path)?; + let real = match self.scope.locate(p) { + Ok(real) => real, + Err(ScriptRead::Missing) => return Err(NOT_FOUND), + Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), + Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), + }; + if !real.is_file() { + return Err(NOT_REGULAR); + } + Ok(real) + } + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. fn charge_write(&mut self, n: usize) -> Result<(), HostError> { self.written = self.written.saturating_add(n); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c191b001a2..cc1a6f5b3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -47,6 +47,10 @@ //! run. An engine keeps no document and no run: its host functions reach the run through a link //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +//! +//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run +//! only after the run's changes are kept, for the frontend to send once the person approves them +//! ([`printing`]). pub mod actions; pub mod console; @@ -54,6 +58,7 @@ pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod printing; pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { + command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value)) +} + +/// [`command`] for a member that keeps the command's result itself: the result does not cross to +/// the script, so it is not held to the limits of a crossing. → the result as the command gave it. +fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result { + command_crossing(host, id, params, false).map(|(_, value)| value) +} + +/// [`command_value`], with the script's copy of the result made only when `cross` is true. +fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option, Value), HostError> { // Point changes that wait in the object model are written before any command runs. dom::flush(host)?; let session = host.session.clone(); @@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( }; let mark = host.growth_mark(); let crossed = host.charge_growth(objects, added).and_then(|()| { + if !cross { + return Ok(None); + } let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; host.charge_call(data_size(&data))?; - Ok(data) + Ok(Some(data)) }); // A command whose result does not reach the script is put back, like one that failed, and so is // the growth it was charged. @@ -1985,6 +2004,22 @@ impl Session { self.script_report.as_ref() } + /// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]). + pub fn script_prints_waiting(&self) -> bool { + !self.script_prints.is_empty() + } + + /// The jobs that wait, as [`Self::take_script_prints`] would give them. + pub fn script_prints(&self) -> &[printing::PreparedPrint] { + &self.script_prints + } + + /// The jobs the last run that printed to a printer prepared, which the session no longer holds: + /// the frontend sends them or drops them ([`printing`]). + pub fn take_script_prints(&mut self) -> Vec { + std::mem::take(&mut self.script_prints) + } + /// The Script Console: the lines of this session's runs, oldest first. pub fn script_console(&self) -> &console::Console { &self.script_console @@ -2344,6 +2379,9 @@ impl Session { ), linked: std::cell::OnceCell::new(), }); + // The printers the frontend listed are this run's alone, and a run may not print while + // jobs an earlier run prepared still wait for the person. + host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty()); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { Ok(args) => args, @@ -2641,13 +2679,27 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + // The jobs it prepared for a printer wait for the frontend now that its changes are kept. + let prints = host.dom.take_prints(); + if !prints.is_empty() { + report["prints"] = json!(prints.len()); + self.script_prints = prints; + } let rejections = rejections_report(host, &job.realm); if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) { o.insert("unhandledRejections".into(), Value::Array(rejections)); o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count())); } close_run(self, host, &mut report, console::Ending::Finished); + let tool = host.dom.chosen_tool(); self.end_job(job, false); + // The tool `app.selectTool` chose last becomes the current tool, as a choice on the + // toolbar makes it; the run's changes are kept when the tool cannot be chosen. + if let Some(id) = tool + && let Err(e) = self.select_tool(id, self.last_view) + { + report["toolError"] = json!(e.to_string()); + } self.script_report = Some(report.clone()); Ok(report) } @@ -2886,6 +2938,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: makes the next command a member runs past the script fence panic before it runs. + pub(crate) static PANIC_WHILE_UNFENCED: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; /// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`]. diff --git a/crates/engine/src/script/printing.rs b/crates/engine/src/script/printing.rs new file mode 100644 index 0000000000..f33a12113b --- /dev/null +++ b/crates/engine/src/script/printing.rs @@ -0,0 +1,101 @@ +//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]), +//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print` +//! prepares ([`PreparedPrint`]). +//! +//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and +//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When +//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`]) +//! for the frontend, which sends them only when the person at the computer approves them. +//! +//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or +//! a command line. +//! +//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`], +//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`]. + +/// The most printers a run lists. +pub const MAX_PRINTERS: usize = 256; +/// The longest printer name a run lists, in bytes. +pub const MAX_PRINTER_NAME_BYTES: usize = 512; +/// The most printer jobs one run prepares. +pub const MAX_JOBS: usize = 4; +/// The most sheets of paper the jobs of one run hold together, every copy counted. +pub const MAX_SHEETS: u64 = 100; +/// The most bytes the jobs of one run hold together. +pub const MAX_JOB_BYTES: usize = 32 << 20; + +/// The printers a frontend lists for a run, by name, with the system's default printer. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Printers { + names: Vec, + default: Option, + /// The printer turns no landscape page to fit its paper: jobs are written upright + /// (`file.print`'s `forPrinter`). + pub for_printer: bool, +} + +impl Printers { + /// The printers of `list` (name, whether it is the default), in its order. A name that is + /// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and + /// so is a name that repeats an earlier one, though its default mark is kept. Every printer + /// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the + /// last place when it comes later. + pub fn new(list: impl IntoIterator, for_printer: bool) -> Self { + let mut names: Vec = Vec::new(); + let mut default = None; + for (name, is_default) in list { + let full = names.len() >= MAX_PRINTERS; + if full && default.is_some() { + break; + } + if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) { + continue; + } + if let Some(i) = names.iter().position(|n| *n == name) { + if is_default && default.is_none() { + default = Some(i); + } + continue; + } + if full { + if is_default && let Some(last) = names.last_mut() { + *last = name; + default = Some(MAX_PRINTERS - 1); + } + continue; + } + if is_default && default.is_none() { + default = Some(names.len()); + } + names.push(name); + } + Self { names, default, for_printer } + } + + /// The printers' names. + pub fn names(&self) -> &[String] { + &self.names + } + + /// The system's default printer, when the list holds it. + pub fn default_name(&self) -> Option<&str> { + self.default.map(|i| self.names[i].as_str()) + } + + /// Whether the list holds a printer named exactly `name`. + pub fn has(&self, name: &str) -> bool { + self.names.iter().any(|n| n == name) + } +} + +/// A job a run prepared for a printer: a print-ready PDF, every copy in it. +#[derive(Clone, Debug, PartialEq)] +pub struct PreparedPrint { + /// The printer, by the name the run's list gave it. + pub printer: String, + /// The title of the document it prints, the job's name in the print queue. + pub title: String, + pub pdf: Vec, + /// The sheets of paper it prints, every copy counted. + pub sheets: u64, +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 8a9eea3b4a..4669876304 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -192,6 +192,9 @@ impl Session { script_high_water: Default::default(), script_style_trail: Default::default(), script_in_run: false, + script_unfenced: None, + script_printers: None, + script_prints: Vec::new(), window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..bb8982b0cf 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -545,6 +545,8 @@ impl Session { effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), + active_appearance_item: None, + revision: st.revision, preview: None, tool: false, paint, @@ -572,6 +574,8 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } + self.restore_preview_appearance_item(); + let before_item = self.active_appearance_item.clone(); // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the // Shape Builder), paint previews of that kind change only the colors it paints with, so each // preview starts from the colors the interaction began with; so does a preview with @@ -638,8 +642,11 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + let after_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.active_appearance_item = + (before_item != after_item).then_some(crate::interaction::PreviewAppearanceItem { before: before_item, after: after_item }); it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). @@ -757,8 +764,18 @@ impl Session { } } + fn restore_preview_appearance_item(&mut self) { + let changed = self.active_mut().and_then(|st| st.interaction.as_mut()).and_then(|it| it.active_appearance_item.take()); + if let Some(changed) = changed + && self.active_appearance_item == changed.after + { + self.active_appearance_item = changed.before; + } + } + pub fn cancel_interaction(&mut self) -> Result<()> { self.put_back_interaction(); + self.restore_preview_appearance_item(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index eec49be0c7..90f5f024dd 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -104,7 +104,7 @@ impl Session { return Err(EngineError::PluginBusy); } // A step of a batch a script runs is held to the same rule as the script's own commands. - if self.script_in_run && crate::script::refused_to_scripts(id) { + if self.script_in_run && crate::script::refused_to_scripts(id) && self.script_unfenced != Some(id) { return Err(EngineError::Other(crate::script::refused_text(id))); } // An edit the active tool is computing on another thread (a Shape Builder merge) is diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 8e9eddeeff..5991d656ee 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -219,6 +219,64 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { Ok(bytes) } +/// What [`read_capped_plain`] tells a path that is not a plain file. +pub(crate) const NOT_PLAIN: &str = "not a plain file"; + +/// Whether `m`, read without following a link, is a plain file: not a link, a folder or (on Windows) +/// a junction or other reparse point. +pub(crate) fn is_plain(m: &std::fs::Metadata) -> bool { + m.file_type().is_file() && !reparse_point(m) +} + +/// Whether `m`, read without following a link, is a link (on Windows also a junction or other +/// reparse point). +pub(crate) fn is_link_entry(m: &std::fs::Metadata) -> bool { + m.file_type().is_symlink() || reparse_point(m) +} + +/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without +/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and +/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check +/// is refused with [`NOT_PLAIN`] rather than read. +pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result, String> { + let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) { + Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(), + _ => e.to_string(), + })?; + let m = file.metadata().map_err(|e| e.to_string())?; + if !m.file_type().is_file() || reparse_point(&m) { + return Err(NOT_PLAIN.to_string()); + } + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err(too_large(max)); + } + Ok(bytes) +} + +/// `path` opened for reading, without following a link there. A pipe put in its place does not hold +/// the open up. +#[cfg(unix)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::unix::fs::OpenOptionsExt; + let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK; + std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path) +} + +/// `path` opened for reading; a link or junction there is opened itself, not its target. +#[cfg(windows)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path) +} + +#[cfg(not(any(unix, windows)))] +fn open_no_link(path: &Path) -> std::io::Result { + std::fs::File::open(path) +} + /// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and /// [`Session::finish_plugin_loads`] install. pub(crate) enum PluginLoad { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index acc6cce87f..edb9a1e631 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -190,7 +190,9 @@ mod script_folder; mod script_include; mod script_io; mod script_modules; +mod script_print; mod script_run; +mod script_save_open; mod script_scriptui; mod script_styles; mod script_tags; @@ -1516,6 +1518,7 @@ fn a_boolean_given_as_text_for_a_transform_is_an_error() { ("object.move", json!({"dx": 5, "copy": "true"}), "copy"), ("object.move", json!({"dx": 5, "objects": 0}), "objects"), ("object.nudge", json!({"dx": 1, "big": "true"}), "big"), + ("object.nudge", json!({"dx": 1, "fine": "true"}), "fine"), ("object.rotate", json!({"angle": 45, "absolute": "true"}), "absolute"), ("object.scale", json!({"sx": 200, "strokes": "false"}), "strokes"), ("object.scale", json!({"sx": 200, "corners": [true]}), "corners"), @@ -4495,11 +4498,14 @@ fn stale_current_layer_id_never_targets_a_reused_id() { s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); assert_eq!(c, layer, "precondition: id reused"); + // Undo gives back the layer that was current before New Layer; a remembered id left over + // from elsewhere still names the compound path now. + s.doc_mut().unwrap().active_layer = Some(c); let d = rect(&mut s, 50.0, 50.0, 10.0, 10.0); s.execute("select.set", &json!({"ids": [d.0]})).unwrap(); s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap(); let doc = &s.doc().unwrap().doc; - assert!(doc.node(c).unwrap().children().unwrap().iter().all(|n| n.path_data().is_some())); + assert_eq!(doc.node(c).unwrap().children().unwrap().len(), 2, "the compound path holds only the two rectangles it was made from"); assert!(doc.parent_of(d).is_some_and(|p| doc.node(p).unwrap().is_layer())); // layer.delete without an id must not delete the compound path. s.execute("layer.delete", &json!({})).ok(); diff --git a/crates/engine/src/tests/areafit.rs b/crates/engine/src/tests/areafit.rs index 7d8f759cf5..046271982f 100644 --- a/crates/engine/src/tests/areafit.rs +++ b/crates/engine/src/tests/areafit.rs @@ -374,52 +374,6 @@ fn auto_height_in_columns_matches_the_full_search_when_lines_start_small() { } } -/// Time typing at the start of a story of 5,000, 20,000 and 50,000 characters in Auto Size area -/// type in 2 and 3 columns: 20 letters typed one at a time with the Type tool, with Auto Size as it -/// runs and with `FULL_SEARCH` on (the columns laid out at every step of the bisection). -/// Run with `cargo test --release -p vectorcraft-engine --lib auto_height_in_columns_typing_timing -- --ignored --nocapture`. -#[test] -#[ignore = "manual timing probe; wall-clock performance depends on machine load"] -fn auto_height_in_columns_typing_timing() { - use crate::cmd::typecmd::{COLUMN_LAYOUTS, FULL_SEARCH}; - const WORDS: &str = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame of this story. "; - let v = ViewInfo::default(); - for n in [5_000, 20_000, 50_000] { - let story = format!("{}\n", WORDS.repeat(6).trim_end()).repeat(n / 600 + 1)[..n].to_string(); - for cols in [2, 3] { - let mut row = format!("{n} characters in {cols} columns:"); - for full in [false, true] { - FULL_SEARCH.with(|c| c.set(full)); - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 4400, "height": 1200})).unwrap(); - let area = json!({"width": 500, "height": 100, "fit": "autoHeight"}); - let id = s.execute("text.create", &json!({"x": 20, "y": 20, "size": 9, "text": story, "area": area})).unwrap()["id"].clone(); - s.execute("select.set", &json!({"ids": [id]})).unwrap(); - s.execute("text.areaOptions", &json!({"columns": cols, "gutter": 12})).unwrap(); - s.select_tool("type", v).unwrap(); - for kind in [PointerKind::Down, PointerKind::Up] { - s.pointer(&PointerEvent::new(kind, 21.0, 24.0), v).unwrap(); - } - let layouts = COLUMN_LAYOUTS.with(std::cell::Cell::get); - let mut ms: Vec = "abcdefghijklmnopqrst" - .chars() - .map(|ch| { - let start = std::time::Instant::now(); - s.tool_text(&ch.to_string(), v).unwrap(); - start.elapsed().as_secs_f64() * 1000.0 - }) - .collect(); - let per_key = (COLUMN_LAYOUTS.with(std::cell::Cell::get) - layouts) as f64 / ms.len() as f64; - ms.sort_by(f64::total_cmp); - let how = if full { "every step laid out" } else { "Auto Size" }; - row += &format!(" {how} {:.1} ms a keystroke ({per_key:.1} column layouts);", ms[ms.len() / 2]); - } - FULL_SEARCH.with(|c| c.set(false)); - println!("{row}"); - } - } -} - #[test] fn shrink_text_round_trips_through_the_native_format() { let mut s = session(); diff --git a/crates/engine/src/tests/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index eec4ee191a..f34a611390 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -553,7 +553,7 @@ fn reset_bounding_box_squares_the_objects_inside_a_group() { // The group and both members, in one step. assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 3); assert_eq!(undo_len(&s), n + 1); - assert!(object_angles(&s).iter().all(|a| *a == 0.0), "{:?}", object_angles(&s)); + assert_eq!(object_angles(&s), [0.0; 3], "the group and both members"); s.execute("object.ungroup", &json!({})).unwrap(); assert_eq!(selection_box(&s).angle, 0.0); assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0); @@ -709,9 +709,11 @@ fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() { let art = (anchors(&s, a), anchors(&s, c)); // The group, the masked object, its mask's art and the other rectangle. assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4); - assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s)); + let turned = object_angles(&s); + assert_eq!(turned.len(), 4, "{turned:?}"); + assert!(turned.iter().all(|x| near(*x, 25.0)), "{turned:?}"); assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4); - assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s)); + assert_eq!(object_angles(&s), [0.0; 4]); assert_eq!((anchors(&s, a), anchors(&s, c)), art); } diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index f2fe9860ca..2e809eaed9 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -1247,10 +1247,13 @@ fn pasted_brushed_art_brings_the_patterns_its_brush_art_uses() { run(&mut s, "brush.apply", json!({"name": "Dotted Band", "ids": [line]})); run(&mut s, "select.set", json!({"ids": [line]})); run(&mut s, "edit.copy", json!({})); + let (brush, dots) = (vectorcraft_brush::find(doc(&s), "Dotted Band"), doc(&s).pattern("Dots").cloned()); run(&mut s, "file.new", json!({"width": 200, "height": 200})); + assert_eq!((vectorcraft_brush::find(doc(&s), "Dotted Band"), doc(&s).pattern("Dots")), (None, None), "a new document has neither"); run(&mut s, "edit.paste", json!({})); - assert!(vectorcraft_brush::find(doc(&s), "Dotted Band").is_some()); - assert!(doc(&s).pattern("Dots").is_some(), "the brush's art is filled with it"); + assert_eq!(vectorcraft_brush::find(doc(&s), "Dotted Band"), brush); + assert_eq!(doc(&s).pattern("Dots").cloned(), dots, "the brush's art is filled with it"); + assert!(dots.is_some()); } #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 03eb4ec5e8..724eaa7e1d 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -913,6 +913,77 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() { assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err()); } +/// `brush.options` that leaves the brush as it is changes neither the document nor its revision, +/// and records no undo step, whether the library is stored or still the defaults. +#[test] +fn brush_options_that_change_nothing_record_no_undo_step() { + let mut s = session(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, st.history.undo.len()) + }; + let before = state(&s); + s.execute("brush.options", &json!({"name": "Arrow", "params": {}})).unwrap(); + assert_eq!(state(&s), before, "unchanged options of a default library change nothing"); + s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 110.25}})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "a changed option is one undo step"); + let before = state(&s); + for p in [ + json!({"name": "Arrow"}), + json!({"name": "Arrow", "params": {}}), + json!({"name": "Arrow", "params": {"width": 110.25}}), + json!({"name": "Arrow", "newName": " Arrow "}), + json!({"name": "Arrow", "newName": ""}), + ] { + assert_eq!(s.execute("brush.options", &p).unwrap()["name"], "Arrow"); + assert_eq!(state(&s), before, "{p} changes nothing"); + } + s.execute("brush.options", &json!({"name": "Arrow", "newName": "Arrow 2"})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step"); +} + +/// `brush.apply` of the brush that the strokes and the current brush already have changes neither +/// the document nor its revision, and records no undo step. +#[test] +fn brush_apply_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, st.history.undo.len()) + }; + let before = state(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1); + let before = state(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(state(&s), before, "applying the brush again changes nothing"); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "making the brush current again is one undo step"); + assert_eq!(s.execute("brush.list", &json!({})).unwrap()["current"], "Charcoal"); + let b = rect(&mut s, 80.0, 10.0, 50.0, 50.0); + let steps = undo_steps(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0, b.0]})).unwrap(); + assert_eq!((brush_of(&s, a).as_deref(), brush_of(&s, b).as_deref()), (Some("Charcoal"), Some("Charcoal"))); + assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step"); +} + +/// Applying the current brush again to a stroke with settings of its own clears them as one undo step. +#[test] +fn brush_apply_clears_object_options_as_one_undo_step() { + let mut s = session(); + let a = line(&mut s); + select(&mut s, &[a]); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + let steps = undo_steps(&s); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({}), "applying the brush clears the stroke's own settings"); + assert_eq!(undo_steps(&s), steps + 1, "clearing the settings is one undo step"); +} + /// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name /// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 6ccdfad0a5..514015066b 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo } /// The Shape Builder tool sends the point where the drag started first and the point where it -/// ended last, so a drag from the hole into the square takes the square's look. +/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the +/// square's look. #[test] fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() { let mut s = session(); @@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() { select_ids(&mut s, &bars.iter().copied().chain([red]).collect::>()); let v = ViewInfo::default(); s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap(); @@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() { let v = ViewInfo::default(); s.select_tool("shapeBuilder", v).unwrap(); let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap(); assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging"); let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true}); s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap(); @@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() { assert_eq!(s.paint.fill, before, "the cancel puts the fill back"); } +/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a +/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape +/// is not the red or blue of the art. +#[test] +fn shape_builder_default_merge_fills_with_the_picked_fill() { + let v = ViewInfo::default(); + for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] { + let mut s = session(); + two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + s.select_tool("shapeBuilder", v).unwrap(); + s.execute("paint.setFill", &pick).unwrap(); + let picked = s.paint.fill.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + let (cmd, params) = s.journal.last().unwrap().clone(); + assert_eq!((cmd.as_str(), ¶ms["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}"); + let d = &s.doc().unwrap().doc; + let fills: Vec = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect(); + assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill"); + } +} + /// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder /// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient. #[test] @@ -2505,6 +2533,9 @@ fn shape_builder_erase_click_or_drag_from_inside_a_narrow_overlap_deletes_it() { assert_eq!(r["edges"].as_u64(), Some(0), "{points}: {r}"); let d = &s.doc().unwrap().doc; let left: Vec = d.children(d.default_layer()).unwrap().iter().filter_map(|c| c.geometric_bounds()).map(|b| b.width()).collect(); + let erased = r["regions"].as_u64().unwrap(); + assert!((1..=3).contains(&erased), "{points}: {r}"); + assert_eq!(left.len() as u64, 3 - erased, "{points}: the regions not erased stay: {left:?}"); assert!(left.iter().all(|w| *w > 2.0), "{points}: no strip is left: {left:?}"); } } @@ -4555,6 +4586,7 @@ fn live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_st s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); s.execute("paint.default", &json!({})).unwrap(); let (faces, edges) = part_looks(&s, g); + assert_eq!((faces.len(), edges.len() >= 4), (3, true), "{}", edges.len()); assert!(faces.iter().all(|f| f.fill_paint().is_none() && f.stroke_paint().is_none())); assert!(edges.iter().all(|e| e.stroke_paint() == Paint::solid(Color::BLACK) && e.stroke_width() == 0.5 && e.fill_paint().is_none())); assert_eq!(sources_looks(&s, g), sources0); @@ -4599,6 +4631,7 @@ fn live_paint_group_invert_recolors_the_faces_fill() { let (_, edges0) = part_looks(&s, g); s.execute("paint.invert", &json!({"stroke": false})).unwrap(); let (faces, edges) = part_looks(&s, g); + assert_eq!((faces.len(), edges.len() >= 4), (3, true), "{}", edges.len()); assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0)))); assert_eq!(edges, edges0); assert_eq!(sources_looks(&s, g), sources0); @@ -4606,12 +4639,14 @@ fn live_paint_group_invert_recolors_the_faces_fill() { s.execute("paint.invert", &json!({"stroke": true, "target": "contents"})).unwrap(); let (faces1, edges1) = part_looks(&s, g); assert_eq!(faces1, faces); + assert_eq!(edges1.len(), edges.len()); assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::WHITE))); assert_eq!(sources_looks(&s, g), sources0); // A gradient edit of the fill goes to the faces only. s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap(); let (faces2, edges2) = part_looks(&s, g); + assert_eq!(faces2.len(), 3); assert!(faces2.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(_)))); assert_eq!(edges2, edges1, "edges take no fill gradient"); assert_eq!(sources_looks(&s, g), sources0); @@ -4646,7 +4681,9 @@ fn live_paint_group_gradient_vector_and_freeform_edits_change_its_faces() { assert_eq!(sources_looks(&s, g), sources0); s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap(); s.execute("paint.freeform.addPoint", &json!({"stroke": false, "at": [25, 50], "color": "#00ff00"})).unwrap(); - assert!(part_looks(&s, g).0.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some()))); + let faces_now = part_looks(&s, g).0; + assert_eq!(faces_now.len(), face_ids.len()); + assert!(faces_now.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some()))); assert_eq!(part_looks(&s, g).1, edges0); assert_eq!(sources_looks(&s, g), sources0); } @@ -4916,16 +4953,19 @@ fn live_paint_group_contents_edits_follow_the_group_rule() { let sources0 = sources_looks(&s, g); s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap(); let (faces1, edges1) = part_looks(&s, g); + assert_eq!((faces0.len(), faces1.len(), edges0.len() >= 4), (3, 3, true), "{}", edges0.len()); assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill"); assert_eq!(edges1, edges0, "edges take no new fill"); s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap(); let (faces2, edges2) = part_looks(&s, g); assert_eq!(faces2, faces1, "faces take no new stroke"); + assert_eq!(edges2.len(), edges1.len()); assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke"); // A stroke row edit of the contents reaches the edges, not the faces. s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap(); let (faces3, edges3) = part_looks(&s, g); assert_eq!(faces3, faces2, "faces keep their rows"); + assert_eq!(edges3.len(), edges2.len()); assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight"); s.execute("appearance.clear", &json!({"target": "contents"})).unwrap(); assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance"); @@ -5175,6 +5215,7 @@ fn live_paint_group_contents_take_a_graphic_style_by_kind() { s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap(); assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes"); let (faces, edges) = part_looks(&s, g); + assert_eq!((faces.len(), edges.len() >= 4), (3, true), "add {add}: {}", edges.len()); assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill"); assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke"); let n = node(&s, g); @@ -6171,6 +6212,7 @@ fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_ed let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + assert!(all.len() >= 3, "the outline and the shared edge: {all:?}"); paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]); let v = ViewInfo::default(); s.select_tool("livePaintBucket", v).unwrap(); @@ -9189,16 +9231,23 @@ fn image_trace_refuses_an_unknown_setting() { } } -/// Every preset's settings, as imageTrace.presets lists them, trace when passed back whole. +/// A preset's settings, as imageTrace.presets lists them, trace when passed back whole, and the +/// trace keeps them: a preset with an enhanced version, both ways, and a preset without one. #[test] -fn image_trace_takes_every_preset_back_as_params() { +fn image_trace_takes_a_preset_back_as_params() { let list = session().execute("imageTrace.presets", &json!({})).unwrap(); - for preset in list["presets"].as_array().unwrap() { - for params in [&preset["params"], &preset["enhanced"]].into_iter().filter(|p| !p.is_null()) { - let mut s = session(); - image_doc(&mut s); - let r = s.execute("imageTrace.make", &json!({"preset": preset["name"], "params": params})); - assert!(r.is_ok(), "{}: {r:?}", preset["name"]); + let preset = |name: &str| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).unwrap().clone(); + let (six, flat) = (preset("6 Colors"), preset("Flat Logo")); + for (name, params) in [("6 Colors", &six["params"]), ("6 Colors", &six["enhanced"]), ("Flat Logo", &flat["params"])] { + let mut s = session(); + image_doc(&mut s); + let r = s.execute("imageTrace.make", &json!({"preset": name, "params": params})).unwrap(); + let stored = node(&s, NodeId(r["id"].as_u64().unwrap())).extras().trace.clone().unwrap(); + assert_eq!(stored["preset"], name); + let given = params.as_object().unwrap(); + assert!(given.len() > 1, "{name}: {params}"); + for (key, value) in given { + assert_eq!(&stored["params"][key], value, "{name}: `{key}` is kept"); } } } diff --git a/crates/engine/src/tests/cancel.rs b/crates/engine/src/tests/cancel.rs index 9a044ead89..b369db85cb 100644 --- a/crates/engine/src/tests/cancel.rs +++ b/crates/engine/src/tests/cancel.rs @@ -87,5 +87,10 @@ fn nothing_is_cancelled_outside_a_scope() { token.cancel(); // The token only counts for work run under it, on its thread. let mut s = session(1); - assert!(s.execute("document.exportPdf", &json!({})).is_ok()); + let r = cancel::scope(&token, None, || s.execute("document.exportPdf", &json!({}))); + assert!(matches!(r, Err(EngineError::Cancelled)), "under the token: {r:?}"); + let r = s.execute("document.exportPdf", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + assert!(bytes.starts_with(b"%PDF-"), "outside it the whole file is written"); + assert!(bytes.ends_with(b"%%EOF"), "to its end"); } diff --git a/crates/engine/src/tests/clippaint.rs b/crates/engine/src/tests/clippaint.rs index 1355c11b7d..0d596fe3b2 100644 --- a/crates/engine/src/tests/clippaint.rs +++ b/crates/engine/src/tests/clippaint.rs @@ -155,5 +155,7 @@ fn type_as_a_clipping_path_paints_its_characters() { let p = paint(&s); assert!(p.stroke.is_none()); let NodeKind::Text(fill) = &p.fill.expect("the characters' fill paints").kind else { panic!("type") }; - assert!(fill.runs.iter().all(|r| r.style.fill.color().is_some() && r.style.stroke.is_none())); + assert_eq!(fill.plain_text(), "Clip"); + let blue = vectorcraft_color::Color::from_hex("#0000ff"); + assert!(!fill.runs.is_empty() && fill.runs.iter().all(|r| r.style.fill.color() == blue && r.style.stroke.is_none()), "{:?}", fill.runs); } diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index fecd16ed2a..2ac70f800d 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1160,9 +1160,10 @@ fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() { assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}"); } -/// A Difference square over a white square in a 50 % group that isolates its blending, over the -/// edge between black and white art: the square blends only with the white inside the group, so +/// A Difference square over a 50 % white square in a 50 % group that isolates its blending, over +/// the edge between black and white art: the square blends only with the white inside the group, so /// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer. +/// Without isolation the blend also reaches that art, and there is no one answer. #[test] fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let mut s = session(); @@ -1177,14 +1178,33 @@ fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + // Translucent, so that a blend that is not isolated also reaches the art behind the group. + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap()); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); - s.execute("object.group", &json!({"ids": [back, square]})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [back, square]})).unwrap()); s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap(); s.execute("select.set", &json!({"ids": [square]})).unwrap(); - s.execute("color.contrast", &json!({})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let isolated = ratio(&r); + assert!(isolated > 1.0, "{r}"); + assert!(r["against"].as_str().is_some_and(|h| vectorcraft_color::Color::from_hex(h).is_some()), "{r}"); + // Without isolation the square also blends with the black and white art, so there is no one answer. + let set_isolate = |s: &mut Session, on: bool| { + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": on})).unwrap(); + s.execute("select.set", &json!({"ids": [square]})).unwrap(); + }; + set_isolate(&mut s, false); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("is not one color where it is read"), "{e}"); + set_isolate(&mut s, true); + // The Difference mode is applied: in Normal mode the same square gives another answer. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + let normal = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + assert!((isolated - normal).abs() > 0.1, "difference {isolated} against normal {normal}"); } /// With a fill of None, what a pick would be measured against is still read: the Color Wheel's diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 46d03c0379..55ed42ec7a 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -739,7 +739,9 @@ fn separations_preview_compares_the_visible_plates_as_a_set() { assert_eq!(sep(&mut s, json!({"plates": ["Cyan", "Magenta", "Yellow", "Black"]})), all, "every plate in plate order"); sep(&mut s, json!({"plates": ["Cyan", "Cyan"]})); let r = s.execute("view.separationsPreview", &json!({"toggle": "Cyan"})).unwrap(); - assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}"); + let plates = r["plates"].as_array().unwrap(); + assert_eq!(plates.len(), 4, "{r}"); + assert!(plates.iter().all(|p| p["visible"] == false), "{r}"); } /// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order. diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 9a26e45867..24b5a063d6 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -345,7 +345,9 @@ fn constrain_angle_turns_the_new_objects_bounding_box() { let id = NodeId(s.execute("shape.polarGrid", &json!({"x": 0, "y": 0, "width": 40, "height": 20, "rotation": -30})).unwrap()["id"].as_u64().unwrap()); let n = s.doc().unwrap().doc.node(id).unwrap().clone(); - assert!(n.children().unwrap().iter().all(|c| close(c.bbox_angle, 30.0))); + let lines = n.children().unwrap(); + assert!(lines.len() > 1, "{}", lines.len()); + assert!(lines.iter().all(|c| close(c.bbox_angle, 30.0))); s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "rotation": -30})).unwrap(); assert!(close(selection_rotation(&s), 30.0)); s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi"})).unwrap(); diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs index 36761466ae..f73355c971 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -835,9 +835,10 @@ fn perspective_grid_commands_refuse_a_boolean_given_as_text() { /// For an object in perspective, Move in Perspective by 0 (along its plane or its normal), /// Transform in Perspective by the identity, Transform Again after each, and a Perspective Selection -/// drag that ends where it started record no undo step. So do a Move by 0 and a 1 pt Nudge that -/// Snap to Grid takes back to the gridlines the object's edges are on, and Transform Again after -/// each. With Copy, the identity copies the object in one undo step. +/// drag that ends where it started record no undo step. So do a Move by 0 of an object Snap to Grid +/// keeps on the gridlines its edges are on, and Transform Again after it. With Copy, the identity +/// copies the object in one undo step. (A Nudge in Perspective isn't snapped: it moves by its step, +/// see `arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid`.) #[test] fn perspective_moves_that_move_nothing_record_no_undo_step() { let mut s = session(); @@ -869,8 +870,8 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { assert_eq!(s.journal.last().unwrap().0, "perspective.move"); let (undo, redo, _) = history(&s); assert_eq!(((undo, redo), path(&s, a)), ((before.0, before.1), shape.clone()), "a drag back to its start"); - // Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then it - // takes a move by 0 and a 1 pt nudge back there, and Transform Again after each moves nothing. + // Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then a + // move by 0 there, and Transform Again after it, moves nothing. s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); let g = grid(&s); let (_, _, b) = g.plane_bounds(&s.doc().unwrap().doc, &[a]).unwrap(); @@ -881,12 +882,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { with_a_step_to_redo(&mut s); let before = history(&s); let on_grid = path(&s, a); - let calls = [ - ("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})), - ("object.transformAgain", json!({})), - ("perspective.nudge", json!({"dx": 1, "dy": 0})), - ("object.transformAgain", json!({})), - ]; + let calls = [("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})), ("object.transformAgain", json!({}))]; for (c, p) in calls { assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}"); assert_eq!((history(&s), path(&s, a)), (before, on_grid.clone()), "{c} {p}"); @@ -898,7 +894,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { } /// Move in Perspective refuses a `copy`, `perpendicular` or `snap`, Transform in Perspective a `copy`, -/// and Nudge in Perspective a `big` or `copy`, given as text or as another value that is not true or +/// and Nudge in Perspective a `big`, `fine` or `copy`, given as text or as another value that is not true or /// false: the object stays where it is, nothing is copied, and the undo history stays as it was. Null /// is read as the key left out. #[test] @@ -916,7 +912,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() { refuses_non_boolean(&mut s, "perspective.move", &json!({"from": from, "to": to, key: v}), key); } refuses_non_boolean(&mut s, "perspective.transform", &json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": v}), "copy"); - for key in ["big", "copy"] { + for key in ["big", "fine", "copy"] { refuses_non_boolean(&mut s, "perspective.nudge", &json!({"dx": 1, "dy": 0, key: v}), key); } assert_eq!(state(&s), before, "{v}"); @@ -924,7 +920,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() { let calls = [ ("perspective.move", json!({"from": from, "to": to, "copy": null, "perpendicular": null, "snap": null})), ("perspective.transform", json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": null})), - ("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "copy": null})), + ("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "fine": null, "copy": null})), ]; for (i, (c, p)) in calls.into_iter().enumerate() { assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}"); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e406c1b4f2..b8c6f782f1 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1350,7 +1350,9 @@ fn a_stroke_on_a_picked_type_object_without_a_weight_draws() { s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); let part = s.doc().unwrap().selected_symbol_part().unwrap(); let NodeKind::Text(tx) = &part.kind else { panic!("type: {part:?}") }; - assert!(tx.runs.iter().all(|r| r.style.stroke_width == 1.0 && !r.style.stroke.is_none()), "{:?}", tx.runs); + assert_eq!(tx.plain_text(), "Hi"); + let red = Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + assert!(!tx.runs.is_empty() && tx.runs.iter().all(|r| r.style.stroke_width == 1.0 && r.style.stroke == red), "{:?}", tx.runs); } /// The colors the Fill and Stroke proxies show, as `paint.proxies` replies them. diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index 52a8ff08a3..e90aec1df9 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -417,6 +417,7 @@ fn a_search_skips_font_files_too_large_to_add() { /// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its /// resource fork, which only macOS keeps. A search finds it, and Add Fonts copies it with its fork. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn suitcase_fonts_are_found_and_copied_with_their_fork() { use vectorcraft_testkit::fonts::{renamed, suitcase_fork}; diff --git a/crates/engine/src/tests/freeform.rs b/crates/engine/src/tests/freeform.rs index 99810296ef..dda0f04cc4 100644 --- a/crates/engine/src/tests/freeform.rs +++ b/crates/engine/src/tests/freeform.rs @@ -115,7 +115,9 @@ fn cmyk_stops_recolor_the_points_with_inks() { let id = shape(&mut s, "shape.rectangle", 100.0, 100.0, 100.0, 100.0); run(&mut s, "paint.setFill", json!({"gradient": {"kind": "linear", "stops": cyan_to_black}})); run(&mut s, "paint.editGradient", json!({"kind": "freeform"})); - assert!(points(&s, id).points.iter().all(|p| cyan_and_black(p.color)), "{:?}", points(&s, id).points); + let placed = points(&s, id).points; + assert!(!placed.is_empty()); + assert!(placed.iter().all(|p| cyan_and_black(p.color)), "{placed:?}"); } #[test] @@ -181,6 +183,7 @@ fn reapplied_gradients_place_their_points_afresh() { let other = shape(&mut s, "shape.rectangle", 400.0, 300.0, 100.0, 100.0); run(&mut s, "paint.lastGradient", json!({})); let (a, (b, _)) = (points(&s, id), node(&s, other).proxy_freeform(false, None).unwrap()); + assert!(!a.points.is_empty() && b.points.len() == a.points.len(), "{:?}", b.points); assert!(b.points.iter().all(|p| p.at.x >= 400.0 && p.at.y >= 300.0), "{:?}", b.points); assert_eq!(a.points.iter().map(|p| p.color.to_hex()).collect::>(), b.points.iter().map(|p| p.color.to_hex()).collect::>()); } diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index 14cdb653b5..0c4bc3d0d3 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -38,8 +38,11 @@ fn new_gradient_defaults_follow_the_cmyk_document_mode() { let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); s.execute("paint.editGradient", &json!({"kind":kind})).unwrap(); let g = fill_gradient(&s, id); + assert!(g.gradient.stops.len() >= 2, "{kind}: {:?}", g.gradient.stops); assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "{kind}: {:?}", g.gradient.stops); + assert_eq!(g.freeform.is_some(), kind == "freeform", "{kind}"); if let Some(freeform) = g.freeform { + assert!(!freeform.points.is_empty()); assert!(freeform.points.iter().all(|point| matches!(point.color, Color::Cmyk { .. })), "freeform points must use the same color model"); } } @@ -52,6 +55,7 @@ fn editing_an_explicit_rgb_gradient_in_cmyk_keeps_its_color_model() { let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); s.execute("paint.editGradient", &json!({"kind":"linear","keepModel":true})).unwrap(); let before = fill_gradient(&s, id).gradient.stops; + assert_eq!(before.len(), 2, "{before:?}"); assert!(before.iter().all(|stop| matches!(stop.color, Color::Rgb { .. }))); s.execute("paint.editGradient", &json!({"angle":45})).unwrap(); assert_eq!(fill_gradient(&s, id).gradient.stops, before); @@ -67,6 +71,7 @@ fn drawing_a_new_gradient_vector_uses_cmyk_default_stops() { let appearance = &node(&s, id).appearance; let paint = if stroke { appearance.stroke_paint() } else { appearance.fill_paint() }; let Paint::Gradient(g) = paint else { panic!("not a gradient") }; + assert_eq!(g.gradient.stops.len(), 2, "stroke={stroke}: {:?}", g.gradient.stops); assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "stroke={stroke}: {:?}", g.gradient.stops); } } diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index 9a48655468..a5ec82dd28 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -25,10 +25,15 @@ fn ids_stand_in_for_the_selection() { ("object.makePixelPerfect", json!({})), ] { let (mut s, id) = doc_with_rect(); + assert!(s.execute(cmd, ¶ms).is_err(), "{cmd}: nothing selected and no ids"); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); let mut p = params; p["ids"] = json!([id]); let r = s.execute(cmd, &p); assert!(r.is_ok(), "{cmd}: {r:?}"); + let st = s.doc().unwrap(); + assert_ne!(st.doc, before, "{cmd}: the object given is changed"); + assert_eq!(st.history.undo.len(), undo + 1, "{cmd}: one undo step"); } } @@ -523,6 +528,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() { ("addon.cleanup.deepUngroup", json!({}), rect), ("addon.cleanup.rejoin", json!({}), rect), ("addon.color.nearestSwatch", json!({}), rect), + ("addon.color.randomFill", json!({"seed": 1}), rect), ("addon.pathtools.cornerSet", json!({"radius": 2}), rect), ("addon.pathtools.cornerRemove", json!({}), rect), ("addon.pathtools.shape.convert", json!({}), rect), diff --git a/crates/engine/src/tests/keyguide.rs b/crates/engine/src/tests/keyguide.rs index 327c0b4b24..4be2679bc9 100644 --- a/crates/engine/src/tests/keyguide.rs +++ b/crates/engine/src/tests/keyguide.rs @@ -174,10 +174,10 @@ fn guides_align_to_a_key_object_among_others_and_parallel_ones_to_a_key_guide() s.execute("select.key", &json!({"id": b.0})).unwrap(); s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert_eq!(bounds(&s, a).x0, 300.0); - assert!(positions(&s).iter().all(|p| *p == 300.0)); + assert_eq!(positions(&s), [300.0, 300.0], "both guides"); // Aligning to the selection leaves guides alone. s.execute("object.align", &json!({"horizontal": "right", "to": "selection"})).unwrap(); - assert!(positions(&s).iter().all(|p| *p == 300.0)); + assert_eq!(positions(&s), [300.0, 300.0]); // A key guide stays put, and the other vertical guide lines up on it. s.execute("guide.move", &json!({"index": 1, "pos": 700})).unwrap(); s.execute("select.key", &json!({"guide": 1})).unwrap(); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 0394fb18fa..19cbe75c56 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -253,6 +253,24 @@ fn transform_each_with_copy_of_50000_objects_takes_few_tree_walks() { undo_gives_back(&mut s, &before); } +/// A move of 10,000 selected objects walks the tree once for the paint order and the top-level +/// objects, once for Transform Patterns and the edit, and once for the selection's check after the +/// edit. It reads each object's compound path at the object's place, so the only lookups by id are +/// the range check's, one per object. +#[test] +fn moving_10000_selected_objects_walks_the_tree_three_times() { + let n = 10_000; + let mut s = session(n, square); + let ids = layer(&s, 0); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + let (walks, lookups) = (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups); + assert_eq!(walks, 3, "walked the tree {walks} times"); + assert!(lookups <= n as u64, "{lookups} lookups by id for {n} objects"); + assert_eq!(bounds(&s, ids[n - 1]), square_at(n - 1) + vectorcraft_geom::Vec2::new(3.0, 0.0)); + assert!(selected(&s, &ids)); +} + #[test] fn offset_path_of_50000_objects_takes_few_tree_walks() { let s = session(50_000, square); @@ -417,7 +435,7 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() { assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy")); // The squares stay; their copies move together. let moved = bounds(&s, copies[0]).origin() - square_at(0).origin(); - assert!(moved.x > 0.0, "{moved:?}"); + assert!((moved.x - 80.0).abs() < 1e-6 && moved.y.abs() < 1e-6, "the copies move by the drag: {moved:?}"); for (k, (id, copy)) in ids.iter().zip(&copies).enumerate() { assert_eq!(bounds(&s, *id), square_at(k)); assert_eq!(bounds(&s, *copy), square_at(k) + moved); diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index e39cf66896..ebc2b5d1c6 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -189,6 +189,7 @@ fn a_path_on_a_mapped_drive_is_on_the_share_behind_it() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_mapped_drives_share_are_followed() { use crate::cmd::fileio::{document_path_with, share_of}; @@ -208,6 +209,7 @@ fn links_on_a_mapped_drives_share_are_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_drive_mapped_to_another_share_are_not_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; @@ -228,6 +230,7 @@ fn links_on_a_drive_mapped_to_another_share_are_not_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_the_documents_share_or_this_computer_are_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index cd844fa28d..26f6ca51ce 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() { let mut s = session(); let id = place(&mut s, &pic); run(&mut s, "select.set", json!({"ids": [id.0]})); - assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}})); + assert_eq!( + run(&mut s, "links.placementOptions", json!({})), + json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}}) + ); let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true})); assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}})); assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err()); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index b4aad6c7e6..6896802a68 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4113,7 +4113,8 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() { let before = history(&s); let r = s.execute("type.smartPunctuation", &json!({})).unwrap(); assert_eq!(r["changed"], 0, "{id:?}"); - assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}"); + let none = json!({"fiLigatures": 0, "flLigatures": 0, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0}); + assert_eq!(r["replaced"], none, "{id:?}: {r}"); assert_eq!(history(&s), before, "{id:?}"); } assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…"); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..6e1623c00e 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() { } } +/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside +/// 1 to 1000 is an error, not rounded or clamped to one. +#[test] +fn counts_that_are_not_whole_or_out_of_range_are_errors() { + for p in [ + json!({"artboards": 2.4}), + json!({"artboards": 0}), + json!({"artboards": -0.5}), + json!({"artboards": 1001}), + json!({"artboardLayout": {"columns": 2.4}}), + json!({"artboardLayout": {"columns": 1001}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}), + ] { + let mut s = Session::new(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}: no document on an error"); + } + let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}})); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count"); +} + +#[test] +fn replaying_a_journal_rounds_an_older_artboard_count() { + let mut recorded = new_doc(json!({"artboards": 2})); + recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + assert_eq!(boards(&s).len(), 2); + assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err()); +} + +#[test] +fn replayed_counts_keep_their_rounding_and_range_rules() { + for (key, value, expected) in [ + ("artboards", 0.0, 1), + ("artboards", 1001.0, 1000), + ("columns", 2.4, 2), + ("columns", 1001.0, 1000), + ("rows", 2.4, 2), + ("rows", 0.6, 1), + ("rows", 1000.4, 1000), + ] { + let mut p = json!({"width": 10, "height": 10, "artboards": 4, + "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); + if key == "artboards" { + p[key] = json!(value); + } else { + p["artboardLayout"][key] = json!(value); + } + let mut s = Session::new(); + s.replay("file.new", &p).unwrap(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + if key == "artboards" { + p[key] = json!(expected); + } else { + p["artboardLayout"][key] = json!(expected); + } + assert_eq!(boards(&s), boards(&new_doc(p))); + } + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + let mut p = json!({"artboardLayout": layout}); + p["artboardLayout"]["layout"] = json!("gridByColumn"); + let mut s = Session::new(); + assert!(s.replay("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}"); + } +} + #[test] fn categories_list_generated_presets_with_neutral_names() { let mut s = Session::new(); @@ -631,13 +704,14 @@ fn rearrange_refuses_bad_indices_and_at() { assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); } -/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). -fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet), +/// inside the returned temporary folder, which is removed when dropped, also when the test fails. +fn with_profiles(name: &str) -> (Session, std::path::PathBuf, vectorcraft_testkit::TempDir) { + let root = vectorcraft_testkit::TempDir::new(&format!("newdoc-profiles-{name}")); + let dir = root.join(format!("vc-newdoc-profiles-{name}")); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); - (s, dir) + (s, dir, root) } fn swatch_names(s: &Session) -> Vec { @@ -705,7 +779,7 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { #[test] fn an_edited_profile_starts_the_documents_of_its_category() { - let (mut s, dir) = with_profiles("edited"); + let (mut s, dir, _root) = with_profiles("edited"); let listed = s.execute("file.newProfiles", &json!({})).unwrap(); let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); @@ -733,7 +807,6 @@ fn an_edited_profile_starts_the_documents_of_its_category() { s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); - let _ = std::fs::remove_dir_all(&dir); } /// The fill, stroke and weight of `id` in the active document. @@ -745,7 +818,7 @@ fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::P #[test] fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("default-style"); + let (mut s, _, _root) = with_profiles("default-style"); // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); @@ -796,12 +869,11 @@ fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke assert_eq!(s.paint.fill, green); s.execute("paint.default", &json!({})).unwrap(); assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_profile_follows_the_preset_access_and_reset() { - let (mut s, dir) = with_profiles("choice"); + let (mut s, dir, _root) = with_profiles("choice"); edit_print_profile(&mut s, &dir); // A request that may not read the folder gets the defaults, and the reason; edit is refused // before anything is written. @@ -841,7 +913,6 @@ fn the_profile_follows_the_preset_access_and_reset() { assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The first run's style of text object `id`. @@ -853,7 +924,7 @@ fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle { #[test] fn a_profiles_normal_character_style_is_the_default_font() { - let (mut s, dir) = with_profiles("default-font"); + let (mut s, _, _root) = with_profiles("default-font"); // The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"}); @@ -891,13 +962,12 @@ fn a_profiles_normal_character_style_is_the_default_font() { let st = first_run(&s, &made["id"]); let default = vectorcraft_doc::CharStyle::default(); assert_eq!((st.font_family, st.size), (default.font_family, default.size)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults"); + let (mut s, _, _root) = with_profiles("apply-defaults"); const GLOW: &str = r#""#; // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. @@ -987,7 +1057,6 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); assert_eq!(s.doc().unwrap().history.step(), step); - let _ = std::fs::remove_dir_all(&dir); } /// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's @@ -995,7 +1064,7 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { #[test] fn profile_defaults_stay_with_an_unrelated_object_selected() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults-selected"); + let (mut s, _, _root) = with_profiles("apply-defaults-selected"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); s.execute("paint.setFill", &json!({"none": true})).unwrap(); @@ -1013,7 +1082,6 @@ fn profile_defaults_stay_with_an_unrelated_object_selected() { assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); - let _ = std::fs::remove_dir_all(&dir); } /// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open @@ -1026,7 +1094,7 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { "roman": {"font": "JetBrains Mono", "size": roman}, }}) }; - let (mut s, dir) = with_profiles("apply-defaults-composite"); + let (mut s, _, _root) = with_profiles("apply-defaults-composite"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); @@ -1052,12 +1120,11 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(profile(&s), Some(100.0)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { - let (mut s, dir) = with_profiles("errors"); + let (mut s, dir, _root) = with_profiles("errors"); let elsewhere = dir.with_extension("elsewhere"); std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&elsewhere).unwrap(); @@ -1084,22 +1151,19 @@ fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap(); let e = run(&mut s, &inside, "file.newProfiles.reset"); assert!(e.starts_with(&format!("{whole}: ")), "{e}"); - let _ = std::fs::remove_dir_all(&elsewhere); - let _ = std::fs::remove_dir_all(&dir); } /// The new document's links find their files from the profile's file, as a document opened from /// that file does; a document without a profile has no such file. #[test] fn the_new_document_links_from_the_profile_file() { - let (mut s, dir) = with_profiles("links"); + let (mut s, dir, _root) = with_profiles("links"); edit_print_profile(&mut s, &dir); assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print"); let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert_eq!(s.doc().unwrap().links_from, None); - let _ = std::fs::remove_dir_all(&dir); } /// A color profile the profile's file carries is installed when this machine lacks it, as opening @@ -1111,7 +1175,7 @@ fn a_profile_brings_the_color_profile_its_file_carries() { return; } use vectorcraft_color::cms; - let (mut s, dir) = with_profiles("icc"); + let (mut s, dir, _root) = with_profiles("icc"); let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec(); let name = format!("Profile RGB {}", std::process::id()); @@ -1140,12 +1204,11 @@ fn a_profile_brings_the_color_profile_its_file_carries() { std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap(); let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { - let (mut s, dir) = with_profiles("damaged"); + let (mut s, dir, _root) = with_profiles("damaged"); s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); let defaults = swatch_names(&s); std::fs::create_dir_all(&dir).unwrap(); @@ -1162,23 +1225,84 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); - let _ = std::fs::remove_dir_all(&dir); } #[cfg(unix)] #[test] fn a_profile_that_is_a_link_is_not_followed() { - let (mut s, dir) = with_profiles("link"); + let (mut s, dir, root) = with_profiles("link"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); // A profile the folder held, moved out and linked back in. - let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + let outside = root.join("outside.vectorcraft"); std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); assert!(r.get("profile").is_none(), "{r}"); - let _ = std::fs::remove_file(&outside); - let _ = std::fs::remove_dir_all(&dir); +} + +/// The listing entry of profile `name`. +fn listed_profile(s: &mut Session, name: &str) -> Value { + let listed = s.execute("file.newProfiles", &json!({})).unwrap(); + listed["profiles"].as_array().unwrap().iter().find(|p| p["name"] == name).cloned().unwrap() +} + +#[cfg(unix)] +#[test] +fn a_linked_profile_is_listed_as_unusable_and_reset_removes_the_link() { + use crate::cmd::newdoc::ProfileFile; + let (mut s, dir, root) = with_profiles("linked-listing"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::Plain); + assert!(listed_profile(&mut s, "Print").get("unusable").is_none()); + let outside = root.join("outside.vectorcraft"); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + + // file.new does not read it, so the listing says so, and Edit does not open it. + assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::NotPlain); + assert!(ProfileFile::NotPlain.resettable()); + let p = listed_profile(&mut s, "Print"); + assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}"); + let e = s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap_err().to_string(); + assert!(e.contains("not a plain file"), "{e}"); + // Reset removes the link and leaves the file it led to. + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap()["reset"], true); + assert!(std::fs::symlink_metadata(dir.join("Print.vectorcraft")).is_err() && outside.is_file()); + assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::None); +} + +#[cfg(unix)] +#[test] +fn a_profile_link_to_nothing_is_listed_and_edit_does_not_write_through_it() { + let (mut s, dir, root) = with_profiles("dangling"); + std::fs::create_dir_all(&dir).unwrap(); + let outside = root.join("outside.vectorcraft"); + std::os::unix::fs::symlink(&outside, dir.join("Web.vectorcraft")).unwrap(); + let p = listed_profile(&mut s, "Web"); + assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}"); + assert!(s.execute("file.newProfiles.edit", &json!({"name": "Web"})).is_err()); + assert!(!outside.exists(), "Edit wrote the shipped profile where the link leads"); + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Web"})).unwrap()["reset"], true); +} + +#[test] +fn a_folder_in_a_profiles_place_is_listed_as_unusable() { + let (mut s, dir, _root) = with_profiles("folder"); + std::fs::create_dir_all(dir.join("Mobile.vectorcraft")).unwrap(); + let p = listed_profile(&mut s, "Mobile"); + assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}"); + let e = s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap_err().to_string(); + assert!(e.contains("not a plain file"), "{e}"); + let r = s.execute("file.new", &json!({"profile": "Mobile"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + // Reset does not delete a folder, and Manage Profiles turns it off. + let file = s.new_doc_profile_file("Mobile"); + assert_eq!(file, crate::cmd::newdoc::ProfileFile::Folder); + assert!(file.customized() && !file.resettable()); + let e = s.execute("file.newProfiles.reset", &json!({"name": "Mobile"})).unwrap_err().to_string(); + assert!(e.contains("a folder"), "{e}"); + assert!(dir.join("Mobile.vectorcraft").is_dir()); } #[test] diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index ffa8e83f40..7ae627e546 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); - let before = render(&s); - if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { eprintln!("skipped: built without a font that draws the type"); return; } + let before = render(&s); + assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red"); // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. let red = (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index e73825e86f..d7343e0ae5 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -269,7 +269,8 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({})).unwrap(); let NodeKind::Text(tx) = &node(&s, t).kind else { panic!() }; - assert!(tx.runs.iter().all(|r| r.style.overprint_fill), "type characters, inside the selected group"); + assert_eq!(tx.plain_text(), "Hi"); + assert!(!tx.runs.is_empty() && tx.runs.iter().all(|r| r.style.overprint_fill), "type characters, inside the selected group"); let fill = |s: &Session, id| node(s, id).appearance.fill().unwrap().overprint; assert!(!fill(&s, g), "a gradient with a rich-black stop"); assert!(!fill(&s, spot), "spot blacks need includeSpotBlacks"); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index f0eeefd810..99aa80e419 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -78,7 +78,9 @@ fn two_links_and_a_font_are_collected_and_relinked() { s.doc().unwrap().doc.visit_images(|_, im| paths.push(im.link.clone().unwrap())); paths }; - assert!(link(&s).iter().all(|l| l.path.contains("art"))); + let links = link(&s); + assert_eq!(links.len(), 2, "{links:?}"); + assert!(links.iter().all(|l| l.path.contains("art")), "{links:?}"); // The packaged one opens with the copies, even with the originals gone. std::fs::remove_dir_all(dir.0.join("art")).unwrap(); let r = open(&mut s, &root.join("poster.vectorcraft").to_string_lossy()); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 397c9252b5..c99f58359f 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -266,6 +266,52 @@ fn a_color_with_an_alpha_part_is_refused() { s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap(); } +/// A color param with a component too large to store (past `f32::MAX`, which would be stored as an +/// infinity) is refused and changes nothing, in every form a color is given in: CMYK, `[r, g, b]`, +/// Gray, Lab and a color object. The ends of each range still set the color. +#[test] +fn a_color_with_a_component_too_large_to_store_is_refused() { + let mut s = session(); + let id = rect(&mut s); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [ + json!({"c": f64::MAX, "m": 0, "y": 0, "k": 0}), + json!({"c": 0, "m": 0, "y": 0, "k": 1e308}), + json!([1e300, 0, 0]), + json!([0, 0, -1e300]), + json!({"gray": 1e300}), + json!({"l": 1e300, "a": 0, "b": 0}), + json!({"l": 50, "a": 0, "b": -1e300}), + json!({"model": "rgb", "r": 1e300, "g": 0, "b": 0}), + json!({"model": "cmyk", "c": 0, "m": 1e300, "y": 0, "k": 0}), + ] { + for (cmd, p) in [ + ("artboard.setProps", json!({"index": 0, "color": bad})), + ("artboard.new", json!({"color": bad})), + ("paint.setFill", json!({"ids": [id.0], "color": bad})), + ("paint.setStroke", json!({"ids": [id.0], "color": bad})), + ("swatch.new", json!({"name": "Far", "color": bad})), + ("swatch.new", json!({"colors": ["#00ff00", bad]})), + ("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + assert_eq!(*s.doc().unwrap().doc, *before, "a color too large to store changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + let fill = |s: &Session| node(s, id).appearance.fill_paint().color(); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap(); + assert_eq!(fill(&s), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": [1, 0, 0]})).unwrap(); + assert_eq!(fill(&s).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"gray": 100}})).unwrap(); + assert_eq!(fill(&s), Some(Color::gray(1.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"l": 100, "a": -128, "b": 127}})).unwrap(); + assert_eq!(fill(&s), Some(Color::lab(100.0, -128.0, 127.0))); +} + /// The native format writes an artboard's background color and reads it back. An artboard without /// one is written as before, with no `color` key. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index f4e251638f..802748e407 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1794,12 +1794,16 @@ fn commands_reject_bad_input() { ("object.path.offsetPath", json!({"offset": "abc"})), ("object.path.offsetPath", json!({"offset": 1e300})), ("object.path.simplify", json!({"tolerance": -5})), + ("object.path.simplify", json!({"level": 101})), ("object.path.splitIntoGrid", json!({"rows": 1e9, "columns": -1})), ("text.setStyle", json!({"size": -3})), ("type.createOutlines", json!({})), ("object.pathfinder.divide", json!({"junk": [1, 2]})), ] { - let _ = s.execute(c, &p); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let r = s.execute(c, &p); + assert!(r.is_err(), "{c} {p}: {r:?}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo), "{c} {p}: nothing changes"); } } diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 016b5e6373..b46b412fd6 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -1087,13 +1087,17 @@ fn delete_and_rename_reach_a_graphs_stored_paints() { let mut s = session(); make_dots(&mut s); let g = graph_painted_with(&mut s, "Dots"); + assert_eq!(stored_graph_paints(&s, g).len(), 4, "the series fill and stroke and the value labels' fill and stroke"); s.execute("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); - assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Spots")), "the rename reaches the graph"); + let renamed = stored_graph_paints(&s, g); + assert!(renamed.len() == 4 && renamed.iter().all(|p| is_pattern(p, "Spots")), "the rename reaches the graph: {renamed:?}"); s.execute("edit.undo", &json!({})).unwrap(); - assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Dots"))); + let back = stored_graph_paints(&s, g); + assert!(back.len() == 4 && back.iter().all(|p| is_pattern(p, "Dots")), "{back:?}"); let v = s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); assert_eq!(v["unpainted"], 4, "the series fill and stroke and the value labels' fill and stroke"); - assert!(stored_graph_paints(&s, g).iter().all(Paint::is_none)); + let cleared = stored_graph_paints(&s, g); + assert!(cleared.len() == 4 && cleared.iter().all(Paint::is_none), "{cleared:?}"); s.execute("graph.setData", &json!({"id": g.0, "rows": [[2], [4]]})).unwrap(); assert_eq!(pattern_uses(doc(&s), "Dots"), 0, "the redrawn graph holds no paint of the deleted pattern"); } diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index 957a6c3c2c..226bff66f1 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -104,6 +104,27 @@ fn assert_written(what: &str, d: &Document) { assert!(diff < 0.02 && diff < without / 4.0, "{what}: read back {:.2}% off ({:.2}% without the effects)", diff * 100.0, without * 100.0); } +#[test] +fn raster_pass_keeps_layers_and_a_previously_generated_image() { + use crate::cmd::rasterfx::effect_image; + + let mut d = Document::new(200.0, 200.0); + let art = rect(&mut d, Rect::new(40.0, 40.0, 80.0, 80.0), Color::rgb(1.0, 0.0, 0.0)); + let original_layer = Arc::clone(&d.layers[0]); + let first = effect_image(&mut d, &art, None, 1.0).unwrap(); + let second = effect_image(&mut d, &first, None, 1.0).unwrap(); + + assert_eq!(d.layers.len(), 1); + assert!(Arc::ptr_eq(&d.layers[0], &original_layer)); + assert_eq!(d.images.len(), 2); + + add(&mut d, second); + let rendered = render(&d); + let at = (60 * rendered.width as usize + 60) * 4; + let pixel = &rendered.pixels[at..at + 4]; + assert!(pixel[0] > 240 && pixel[1] < 15 && pixel[2] < 15, "the second pass still reads the first pass's image: {pixel:?}"); +} + #[test] fn groups_layers_type_images_and_symbols_keep_their_raster_effects() { // A group's shadow (one shadow of both members). diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 0ce9b0bf09..ff20447d4c 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -561,6 +561,41 @@ fn transform_again_repeats_a_perspective_scale_and_copies() { assert!(s.execute("perspective.transform", &json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": f64::MAX})).is_err()); } +/// Snap to Grid (on by default) leaves the arrow keys' step alone: art whose edges are on +/// gridlines moves by the step (a tenth of it with Ctrl/Cmd) in one undo step each, instead of +/// being pulled back onto the gridlines and not moving at all. +#[test] +fn arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid() { + let (mut s, id) = persp_session(); + s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); + // A move that ends 0.3 pt past a gridline crossing snaps the corner onto it. + let g = grid(&s); + let b = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0)); + let past = |v: f64| (v / g.cell).ceil() * g.cell + 0.3 - v; + let (c, dv) = (b.center(), Vec2::new(past(b.x0), past(b.y0))); + let (from, to) = (g.to_page(Plane::Right, c).unwrap(), g.to_page(Plane::Right, c + dv).unwrap()); + s.execute("perspective.move", &json!({"from": [from.x, from.y], "to": [to.x, to.y]})).unwrap(); + let on_grid = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0)); + assert!((on_grid.x0 / g.cell - (on_grid.x0 / g.cell).round()).abs() < 1e-6, "{on_grid:?}"); + // The page step measured at the centre of the selection, as `perspective.nudge` measures it. + let page_step = |s: &Session, before: &[Point]| { + let after = plane_pts(s, id, Plane::Right, 0.0); + let h = grid(s).homography(Plane::Right).unwrap(); + let c = bounds_of(before).center(); + h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap() + }; + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let k = s.prefs.keyboard_increment; + for (mods, step) in [(Mods::default(), k), (Mods { cmd: true, ..Default::default() }, k / 10.0)] { + let (before, n) = (plane_pts(&s, id, Plane::Right, 0.0), undo_len(&s)); + s.tool_key(ToolKey::Right, mods, v).unwrap(); + assert_eq!(undo_len(&s), n + 1, "{mods:?}"); + let d = page_step(&s, &before); + assert!((d - Vec2::new(step, 0.0)).hypot() < 1e-6, "{mods:?} {d:?}"); + } +} + #[test] fn arrow_keys_nudge_in_perspective() { let (mut s, id) = persp_session(); @@ -581,6 +616,13 @@ fn arrow_keys_nudge_in_perspective() { let c = bounds_of(&before).center(); let step = h.apply(c + d).unwrap() - h.apply(c).unwrap(); assert!((step - Vec2::new(s.prefs.keyboard_increment, 0.0)).hypot() < 1e-6, "{step:?}"); + // Ctrl/Cmd takes a tenth of a step. + let before = plane_pts(&s, id, Plane::Right, 0.0); + s.tool_key(ToolKey::Right, Mods { cmd: true, ..Default::default() }, v).unwrap(); + let after = plane_pts(&s, id, Plane::Right, 0.0); + let c = bounds_of(&before).center(); + let step = h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap(); + assert!((step - Vec2::new(s.prefs.keyboard_increment / 10.0, 0.0)).hypot() < 1e-6, "{step:?}"); // Alt copies; Shift takes ten steps. s.tool_key(ToolKey::Left, Mods { alt: true, shift: true, ..Default::default() }, v).unwrap(); let copy = *s.doc().unwrap().selection.objects.first().unwrap(); diff --git a/crates/engine/src/tests/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index b4f8d89ca3..d3a6e22b9e 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -496,12 +496,14 @@ fn snap_to_grid_lands_drawn_and_moved_art_on_gridlines() { let n = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); n.anchors().map(|(_, _, an)| g.to_plane(Plane::Left, an.p).unwrap()).collect() }; - assert!(corners(&s).iter().all(|q| on_line(q.x) && on_line(q.y)), "{:?}", corners(&s)); + let drawn = corners(&s); + assert!(drawn.len() == 4 && drawn.iter().all(|q| on_line(q.x) && on_line(q.y)), "{drawn:?}"); // Moved a cell and a bit: it lands a whole cell over. let from = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap(); let to = g.to_page(Plane::Left, Point::new(4.0 * g.cell + 2.0, 2.0 * g.cell)).unwrap(); run(&mut s, "perspective.move", json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y]})); - assert!(corners(&s).iter().all(|q| on_line(q.x) && on_line(q.y)), "{:?}", corners(&s)); + let moved = corners(&s); + assert!(moved.len() == 4 && moved.iter().all(|q| on_line(q.x) && on_line(q.y)), "{moved:?}"); // Without snapping it moves exactly. let before = corners(&s); run(&mut s, "perspective.move", json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "snap": false})); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 00b4cce694..a655002a4d 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -205,6 +205,7 @@ fn stroke_edits_keep_it_aligned() { assert!(whole(&points(&s, id)), "{:?}", points(&s, id)); s.execute("stroke.set", &json!({"weight": 3})).unwrap(); let pts = points(&s, id); + assert_eq!(pts.len(), 4, "{pts:?}"); assert!(pts.iter().all(|(x, y)| (x - x.floor() - 0.5).abs() < 1e-9 && (y - y.floor() - 0.5).abs() < 1e-9), "{pts:?}"); // Inside alignment puts the stroke within the path, so the anchors go back to whole points. s.execute("stroke.set", &json!({"align": "inside"})).unwrap(); @@ -763,8 +764,10 @@ fn objects_on_path_members_stay_on_the_grid() { // Editing the path places the member again, and it goes back on the grid. let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]); s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); - assert!(whole(&points(&s, a)), "path edited: {:?}", points(&s, a)); - assert!(points(&s, a).iter().all(|(_, y)| *y > 105.0), "followed the path: {:?}", points(&s, a)); + let placed = points(&s, a); + assert_eq!(placed.len(), 4, "{placed:?}"); + assert!(whole(&placed), "path edited: {placed:?}"); + assert!(placed.iter().all(|(_, y)| *y > 105.0), "followed the path: {placed:?}"); } fn align_new(s: &Session) -> bool { @@ -1465,6 +1468,7 @@ fn an_instance_snapped_to_the_grid_moves_its_linked_mask() { assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}"); let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect(); let after = mask_points(&s, linked); + assert!(!moved.is_empty() && after.len() == moved.len(), "{after:?} != {moved:?}"); assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}"); assert!(whole(&placed_points(&s, unlinked))); assert_eq!(mask_points(&s, unlinked), unlinked_before); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 00f976ab3f..3dd4959489 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -739,6 +739,8 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f"); write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None)); let mut s = Session::new(); + // A freed buffer that had the blob's address may have been read before, in another test. + let mark = vectorcraft_pdf::read_mark(); s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap(); let d = &s.doc().unwrap().doc; let boards: Vec = d.artboards.iter().map(|a| a.rect).collect(); @@ -748,7 +750,7 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { // The pages are read from the one copy every page's blob keeps: a page that read the file // again would count here. let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap(); - assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once"); + assert_eq!(vectorcraft_pdf::reads_of_since(&blob, mark), 0, "the pages are read from the file read once"); } #[test] diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 4ecff31b3b..54c599d5fd 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1545,10 +1545,10 @@ fn kept_art_follows_the_swatches_once_a_replaced_plugin_paints() { assert_eq!(draw(&s), (WHITE, RED), "without the swatch, the object as it is"); } -/// Whether `px` is within 40 levels of `want` on every channel. A blur leaves the middle of a -/// shape close to its color. +/// Whether `px` is within 2 levels of `want` on every channel. The samples sit well inside their +/// shapes, so a blur changes them only by rounding. fn near(px: [u8; 4], want: [u8; 4]) -> bool { - px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 40) + px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2) } /// A kept raster of a blur over a painted effect is made again when a swatch its piece names @@ -1916,19 +1916,6 @@ fn refresh_takes_objects_in_definition_art() { assert_eq!(listed(&mut s), [kept.0]); } -/// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app -/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its -/// object's stroke is 5 pt wide, and hands the geometry back otherwise. -#[test] -fn stroke_width_test_effect() { - let Some(dir) = std::env::var_os("CRAFT_PLUGIN_PAINTS_WASM") else { return }; - let triangle = PathData::single(SubPath::polyline(&[Point::new(100.0, 230.0), Point::new(300.0, 230.0), Point::new(200.0, 80.0)], true)); - let manifest = r#"{"id":"org.example.strokewidth","name":"Stroke Width (test plug-in)","version":"1","kind":"effect", - "description":"Draws a triangle while the object's stroke is 5 pt wide.","params":{}}"#; - let src = tpl::when_given(manifest, tpl::Given::Input, r#""width":5.0"#, &json!({"objects": [{"path": triangle}]}).to_string()); - std::fs::write(std::path::Path::new(&dir).join("stroke-width-test-effect.wasm"), wat::parse_str(src).unwrap()).unwrap(); -} - /// A filter is given its objects' effect records and their strokes' join, cap and miter limit, and /// may return them. The records are admitted as effect.apply would admit them; one that isn't /// refuses the whole output, and nothing changes. @@ -1978,26 +1965,6 @@ fn filters_set_effects_and_stroke_styles() { } } -/// `CRAFT_PLUGIN_FRAME_WASM=` saves a test filter to try in the app -/// (`rough-frame-test-filter.wasm`): it adds a frame around 60,40–340,260 with a 6 pt stroke with -/// round joins and caps, roughened by the Roughen effect. -#[test] -fn rough_frame_test_filter() { - let Some(dir) = std::env::var_os("CRAFT_PLUGIN_FRAME_WASM") else { return }; - let frame = PathData::single(SubPath::polyline( - &[Point::new(60.0, 40.0), Point::new(340.0, 40.0), Point::new(340.0, 260.0), Point::new(60.0, 260.0)], - true, - )); - let ink = json!({"type": "solid", "color": {"model": "rgb", "r": 0.15, "g": 0.2, "b": 0.45}}); - let out = json!({"objects": [{"name": "Frame", "path": frame, "fills": [], - "strokes": [{"paint": ink, "width": 6, "join": "round", "cap": "round"}], - "effects": [{"id": "distort.roughen", "params": {"size": 2, "detail": 8, "points": "smooth"}}]}]}); - let manifest = r#"{"id":"org.example.frame","name":"Rough Frame (test plug-in)","version":"1","kind":"filter", - "description":"Adds a frame whose stroke is roughened by the Roughen effect.","params":{}}"#; - let src = tpl::returning(manifest, &out.to_string()); - std::fs::write(std::path::Path::new(&dir).join("rough-frame-test-filter.wasm"), wat::parse_str(src).unwrap()).unwrap(); -} - /// A filter keeps data with the document: it writes it with `documentData` in the same undo step as /// its objects (`null` removes it) and reads what it last wrote in `_context.documentData`, which /// no other filter is given. It is the document's foreign data, so the native file keeps it with @@ -2177,11 +2144,13 @@ fn plugins_folder_set_again_after_clearing_installs_its_plugins() { let mut s = session(); let folder = json!({"key": "pluginsFolder", "value": dir.0.display().to_string()}); run(&mut s, "prefs.set", folder.clone()); - assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed from the folder"); + assert_eq!(run(&mut s, "plugin.list", json!({}))["folder"]["loaded"], json!([id]), "installed from the folder"); run(&mut s, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); run(&mut s, "prefs.set", json!({"key": "pluginsFolder", "value": ""})); + assert_eq!(run(&mut s, "plugin.list", json!({}))["folder"]["loaded"], json!(null), "a cleared folder loads nothing"); run(&mut s, "prefs.set", folder); - assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again when the folder is set again"); + assert_eq!(run(&mut s, "plugin.list", json!({}))["folder"]["loaded"], json!([id]), "installed again when the folder is set again"); run(&mut s, "plugin.remove", json!({"id": id})); } @@ -2256,6 +2225,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; @@ -4109,6 +4079,7 @@ fn a_removal_deletes_only_folders_it_marked() { /// Windows keeps a file another program holds open without delete sharing, so the last grant can't /// be removed by deleting `grants.json`. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { use std::os::windows::fs::OpenOptionsExt; diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 28f34e13ab..01493efda5 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -64,6 +64,49 @@ fn set_and_get_keyboard_increment_drives_nudge() { assert!((b.x0 - 15.0).abs() < 1e-9); } +/// Ctrl/Cmd+arrow (`fine`) nudges by a tenth of the keyboard increment, and Shift+Ctrl+arrow +/// (`big` and `fine`) by one increment: art, direct-selected anchors and ruler guides, one undo +/// step per press, and repeated fine nudges add up to whole increments. +#[test] +fn fine_nudge_moves_a_tenth_of_the_keyboard_increment() { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "keyboardIncrement", "value": 5})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let x0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo(&s); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + assert!((x0(&s) - 10.5).abs() < 1e-9, "{}", x0(&s)); + assert_eq!(undo(&s), n + 1, "one undo step per press"); + s.execute("object.nudge", &json!({"dx": -1, "dy": 0, "big": true, "fine": true})).unwrap(); + assert!((x0(&s) - 5.5).abs() < 1e-9, "Shift+Ctrl: one increment, {}", x0(&s)); + for _ in 0..10 { + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + } + assert!((x0(&s) - 10.5).abs() < 1e-9, "ten fine nudges are one increment, {}", x0(&s)); + assert_eq!(undo(&s), n + 12); + + // Direct-selected anchors. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap(); + let p0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p; + let before = p0(&s); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1, "fine": true})).unwrap(); + let d = p0(&s) - before; + assert!(d.x.abs() < 1e-9 && (d.y - 0.5).abs() < 1e-9, "{d:?}"); + + // Ruler guides. + s.execute("select.none", &json!({})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + let pos = s.doc().unwrap().doc.ruler_guides()[0].pos; + assert!((pos - 100.5).abs() < 1e-9, "{pos}"); + + assert!(s.execute("object.nudge", &json!({"dx": 1, "fine": "true"})).is_err()); +} + #[test] fn set_rejects_out_of_range_and_wrong_types() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index b46cd1e572..8ac581993e 100644 --- a/crates/engine/src/tests/rasterfilters.rs +++ b/crates/engine/src/tests/rasterfilters.rs @@ -119,33 +119,23 @@ fn mean_diff(a: &Rendered, b: &Rendered) -> f64 { fn listed_applied_edited_and_undone() { let (mut s, g) = striped(); let list = s.execute("effect.list", &json!({})).unwrap(); - for (id, _) in EFFECTS { - let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed")); - assert_eq!(e["raster"], json!(true), "{id}"); - assert!(e["params"].as_str().unwrap().contains("radius") || id == "blur.radial", "{id}"); - } - let menus: Vec = - EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect(); - assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]); - for (group, menu) in [ - (ARTISTIC.as_slice(), "Artistic"), - (BRUSH_STROKES.as_slice(), "Brush Strokes"), - (DISTORT.as_slice(), "Distort"), - (PIXELATE.as_slice(), "Pixelate"), - (SKETCH.as_slice(), "Sketch"), - (TEXTURE.as_slice(), "Texture"), - (VIDEO.as_slice(), "Video"), - ([("video.ntscColors", "{}")].as_slice(), "Video"), + // A few representative entries, one per kind of submenu, are listed as raster effects. + for (id, menu) in [ + ("blur.radial", "Blur"), + ("sharpen.unsharpMask", "Sharpen"), + ("artistic.cutout", "Artistic"), + ("sketch.chrome", "Sketch"), + ("video.ntscColors", "Video"), ] { - for (id, _) in group { - let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed")); - assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}"); - } + let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed")); + assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}"); } + assert!(list["catalog"].as_array().unwrap().iter().all(|e| e["id"] != "blur.notAnEffect")); + assert!(s.execute("effect.apply", &json!({"effect": "blur.notAnEffect", "ids": [g]})).is_err()); // Numbers far out of range are stored as given and read clamped; the canvas still draws. // Radial Blur's Blur Center is refused outside 0 to 1 instead. let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY"); - for (id, _) in EFFECTS { + for id in ["blur.radial", "sharpen.unsharpMask"] { let defaults = vectorcraft_render::effects::default_params(id).unwrap(); let junk: serde_json::Map = defaults .as_object() @@ -161,11 +151,11 @@ fn listed_applied_edited_and_undone() { assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err()); let _ = render(&s); let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone(); - assert_eq!(n.appearance.effects.len(), 3); + assert_eq!(n.appearance.effects.len(), 2); assert_eq!(n.appearance.effects[0].params["method"], json!("spin"), "defaults fill the rest"); s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"method": "zoom"}})).unwrap(); assert_eq!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects[0].params["method"], json!("zoom")); - for _ in 0..4 { + for _ in 0..3 { s.execute("edit.undo", &json!({})).unwrap(); } assert!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects.is_empty()); diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 664b696fec..6e3ef16476 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -99,6 +99,7 @@ fn a_white_background_makes_effect_images_opaque() { assert_eq!(clear.get_pixel(0, 0)[3], 0, "transparent by default"); s.execute(C, &json!({"background": "white"})).unwrap(); let white = effect_image(&s.doc().unwrap().doc); + assert_eq!(white.dimensions(), clear.dimensions(), "the same image, on white"); assert!(white.pixels().all(|p| p[3] == 255), "every pixel is opaque"); assert_eq!(white.get_pixel(0, 0).0, [255, 255, 255, 255]); // With a clipping mask, the white stays under the art only. diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index fe87c1f7a0..278e7e0f3d 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -250,7 +250,8 @@ fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}"); // recolor.colors keeps the swatch it lists. let listed = run(&mut s, "recolor.colors", json!({})); - assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}"); + let colors = listed["colors"].as_array().unwrap(); + assert!(!colors.is_empty() && colors.iter().all(|c| c["swatch"] == "Ink"), "{listed}"); } #[test] @@ -446,7 +447,9 @@ fn limit_to_library_snaps_new_colours() { let c = color_value(k).unwrap(); c.to_rgb().iter().all(|v| ((v * 5.0).round() - v * 5.0).abs() < 1e-3) }; - assert!(r["map"].as_array().unwrap().iter().all(|row| web(&row["to"])), "{r}"); + let map = r["map"].as_array().unwrap(); + assert_eq!(map.len(), 2, "a row for each color: {r}"); + assert!(map.iter().all(|row| web(&row["to"])), "{r}"); run(&mut s, "recolor.apply", json!({"map": {"#f01020": "#f01020"}, "limitTo": "Web Safe 216"})); let hexes: Vec = run(&mut s, "recolor.colors", json!({}))["colors"].as_array().unwrap().iter().map(|c| c["hex"].clone()).collect(); assert!(hexes.contains(&json!("#ff0033")) && !hexes.contains(&json!("#f01020")), "{hexes:?}"); @@ -1333,10 +1336,11 @@ fn document_model_converts_the_colours_of_a_group_too() { g.swatches.iter().filter_map(|w| w.paint.color()).collect() }; // Group-only edit from the rows, and with explicit group colours. + let cmyk = |cs: &[Color]| cs.len() == 1 && cs.iter().all(|c| c.model() == vectorcraft_color::cms::Model::Cmyk); run(&mut s, "recolor.apply", json!({"map": {"cmyk 0 0 0 50": "#ff0000"}, "group": "Theme", "model": "document"})); - assert!(group(&s).iter().all(|c| c.model() == vectorcraft_color::cms::Model::Cmyk), "{:?}", group(&s)); + assert!(cmyk(&group(&s)), "{:?}", group(&s)); run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#00ff00"], "model": "document"})); - assert!(group(&s).iter().all(|c| c.model() == vectorcraft_color::cms::Model::Cmyk), "{:?}", group(&s)); + assert!(cmyk(&group(&s)), "{:?}", group(&s)); } fn stroke(s: &Session, id: NodeId) -> Color { @@ -1620,7 +1624,7 @@ fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() { let cut = super::menucmds::place_undecodable_png(&mut s); let cb = s.doc().unwrap().doc.node(cut).unwrap().visual_bounds().unwrap(); let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"rect": [cb.x0, cb.y0, cb.x1, cb.y1]}]})); - assert!(r["colors"].as_array().unwrap().iter().all(|k| k == "rgb 255 0 0"), "the undecodable image adds nothing: {r}"); + assert_eq!(r["colors"], json!(["rgb 255 0 0"]), "the undecodable image adds nothing to the red under it: {r}"); } /// A large image is read through about 65,536 pixels: its palette still holds both halves. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb333e91d8..74311f240f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); } +/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the +/// visible bounds. +#[test] +fn control_bounds_hold_the_handles_of_a_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c = p[0], r = p[1];\ + function h(b) { return b[1] - b[3]; }\ + vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\ + vc.log(String(r.controlBounds) === String(r.visibleBounds));", + ); + let heights = out[0].as_array().unwrap(); + let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap()); + // The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve. + assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}"); + assert_eq!(heights[2], json!(true), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); @@ -500,6 +521,7 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command"); // A value close to the reported one but not equal to it is still applied. s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); @@ -560,6 +582,14 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // With the valid item first and the error caught, the run sees the selection unchanged. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\ + catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( &mut s, @@ -865,6 +895,87 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The +/// page items are `g`, `b`, `a` and `c`, topmost first. +fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom"); + (s, g, a, b, c) +} + +/// The ids of the children of `id`, bottom first. +fn children_of(s: &Session, id: NodeId) -> Vec { + s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn nothing_is_placed_below_a_clipping_path() { + let (mut s, g, a, b, c) = clip_group(); + let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // From outside the group, from above the clipping path inside it, a copy, and a copy of the + // clipping path below itself. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, mask = p[4], out = [];\ + var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\ + function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\ + for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\ + vc.log(out);", + ); + let messages = out[0].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 4, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // Directly above the clipping path is allowed, and so is moving the clipping path beside itself. + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);"); + assert_eq!(children_of(&s, g), [c, d, a, b]); + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps)); +} + +#[test] +fn zorder_that_leaves_an_object_in_place_runs_no_command() { + // The topmost art of a layer with a ruler guide above it. + let (mut s, a, b) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap(); + let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone(); + assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art"); + let steps = undo_steps(&s); + let r = + run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(layer_order(&s)[..2], [a, b]); + // The lowest object above a clipping path, and the clipping path itself. + let (mut s, g, a, b, c) = clip_group(); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\ + ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\ + for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);", + ) + .unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(children_of(&s, g), [c, a, b]); + // A change still runs the command. + log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1)); +} + #[test] fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { let (mut s, a, b) = doc(); @@ -940,7 +1051,11 @@ fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); let d = &s.active().unwrap().doc; assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); - assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + if keep { + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "keepEmpty true keeps it, empty"); + } else { + assert!(d.node(compound).is_none(), "keepEmpty false deletes the compound path"); + } } } @@ -972,11 +1087,23 @@ fn a_grid_by_column_takes_the_number_of_rows() { let distinct = |mut v: Vec| { v.sort_unstable(); v.dedup(); - v.len() + v }; let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); - assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + assert_eq!((tops.len(), lefts.len()), (rows, cols), "{layout} {count}"); + // Each artboard's row and column, counted from the top and from the left: a grid by column + // fills each column top to bottom, and the right-to-left grid starts at the rightmost column. + let index = |v: &[i64], x: f64| v.iter().position(|&t| t == x.round() as i64); + let placed: Vec<_> = boards.iter().map(|b| (index(&tops, b.rect.y0), index(&lefts, b.rect.x0))).collect(); + let expected: Vec<_> = (0..count) + .map(|i| match layout { + "GridByRow" => (Some(i / cols), Some(i % cols)), + "GridByCol" => (Some(i % rows), Some(i / rows)), + _ => (Some(i % rows), Some(cols - 1 - i / rows)), + }) + .collect(); + assert_eq!(placed, expected, "{layout} {count}"); } } @@ -1017,7 +1144,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); - assert!(e.contains("rows must be from 1 to 1000"), "{e}"); + assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}"); for layout in ["gridByRow", "row", "column"] { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); @@ -1350,6 +1477,22 @@ fn a_document_preset_is_an_instance_of_its_class() { let mut s = Session::new(); let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); + // A named engine keeps the preset, but in a later run its type name throws, as its settings do. + run(&mut s, "#targetengine keep\nvar held = new DocumentPreset();").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.typename;"); + assert!(e.contains("this is not a DocumentPreset"), "{e}"); +} + +/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its +/// settings. +#[test] +fn a_document_preset_from_an_earlier_run_throws_from_typename_and_to_string() { + let mut s = Session::new(); + run(&mut s, "#targetengine keep\nvar p = new DocumentPreset();").unwrap(); + for member in ["p.width", "p.typename", "p.toString()", "String(p)"] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains("TypeError") && e.contains("not a DocumentPreset"), "{member}: {e}"); + } } /// The values the presets hold count against the run's heap, a value assigned again in place of @@ -1529,6 +1672,23 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +/// `addDocumentNoUI(startupPreset)` makes the document `addDocument(startupPreset)` makes, and +/// ignores the arguments after the preset's name. +#[test] +fn add_document_no_ui_makes_the_startup_presets_document() { + let mut s = Session::new(); + let out = log( + &mut s, + "var a = app.documents.addDocument('Web'); var p = new DocumentPreset(); p.width = 333;\ + var b = app.documents.addDocumentNoUI('Web', p, true);\ + vc.log([b.typename, b.width === a.width, b.height === a.height, b.width === 333, app.documents.length]);", + ); + assert_eq!(out, vec![json!(["Document", true, true, false, 2])]); + let e = failure(&mut s, "app.documents.addDocumentNoUI('No Such Preset');"); + assert!(e.contains("no startup preset called No Such Preset"), "{e}"); + assert_eq!(s.documents().len(), 2); +} + #[test] fn setting_selected_keeps_how_the_other_objects_are_selected() { let (mut s, a, b) = doc(); @@ -1568,16 +1728,19 @@ fn add_document_takes_only_a_document_preset() { #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); // A profile with no file gives the defaults. let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); assert_eq!(out, vec![json!("Document")]); assert_eq!(s.doc().unwrap().links_from, None); - // A script reads the profile's file in the app's own folder. + // A script reads the profile's file in the app's own folder, with no document open from it. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); log(&mut s, "app.documents.addDocument('Print');"); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); @@ -1604,13 +1767,12 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { // A startup preset with no profile reads no file. let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-warning"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); @@ -1628,7 +1790,6 @@ fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); assert!(named, "{lines:?}"); assert_eq!(s.documents().len(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1731,8 +1892,7 @@ fn setters_on_a_stale_item_report_it_before_a_bad_value() { fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_ones() { // `pageItems[0]` is the topmost object, the one made last. let (mut s, _, b) = doc(); - let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("dom-revert"); let path = dir.join("saved.vectorcraft"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { @@ -1748,7 +1908,6 @@ fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_one ); assert_eq!(out, vec![json!(2)]); assert_eq!(s.active().unwrap().doc.node(b).unwrap().name.as_deref(), Some("loaded")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -2016,6 +2175,21 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); } +/// Outside Windows a `\` is part of a file name: `/a\b.svg` is not the open `/a/b.svg`. +#[test] +fn get_is_file_open_keeps_a_backslash_in_a_unix_file_name() { + let (mut s, _, _) = doc(); + let fixture = vectorcraft_testkit::TempDir::new("script-file-open-backslash"); + let dir = fixture.join("a"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("b.svg"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let same = serde_json::to_string(&path.to_string_lossy()).unwrap(); + let backslash = serde_json::to_string(&format!("{}\\b.svg", dir.to_string_lossy())).unwrap(); + let out = log(&mut s, &format!("vc.log(app.getIsFileOpen({same})); vc.log(app.getIsFileOpen({backslash}));")); + assert_eq!(out, vec![json!(true), json!(cfg!(windows))]); +} + #[test] fn a_menu_command_runs_its_command_on_the_selection() { let (mut s, a, b) = doc(); @@ -2116,6 +2290,35 @@ fn prototype_changes_cannot_forge_a_page_item() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); } +#[test] +fn select_tool_makes_the_named_tool_current_when_the_run_ends() { + let (mut s, _, _) = doc(); + assert_eq!(s.tool_id(), "selection"); + // A tool's id, its label and a name in the form scripts pass all choose it; the last one counts. + assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]); + assert_eq!(s.tool_id(), "pen"); + log(&mut s, "app.selectTool('Rectangle Tool');"); + assert_eq!(s.tool_id(), "rectangle"); + log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');"); + assert_eq!(s.tool_id(), "directSelection"); + log(&mut s, "app.selectTool('Adobe Select Tool');"); + assert_eq!(s.tool_id(), "selection"); + // An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool. + assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\"")); + assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named")); + let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }"); + assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]); + assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop")); + let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }"); + assert_eq!(out, vec![json!("TypeError")]); + assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long")); + assert_eq!(s.tool_id(), "selection"); + // With no document open the tool is chosen too. + let mut empty = Session::new(); + log(&mut empty, "app.selectTool('Adobe Freehand Tool');"); + assert_eq!(empty.tool_id(), "pencil"); +} + #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); @@ -2309,8 +2512,17 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); // Each pass edits the document, so nothing kept from the last read can be reused. let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + // The script's fuel, and the host's calls and the bytes they count, which hold the work the + // host does for them: 64 KiB is less than one list of the large document's objects. + let cost = |s: &mut Session| { + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let r = run(s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let r = r.unwrap_or_else(|e| panic!("the reads went over: {e}")); + (r["fuelUsed"].as_u64().unwrap(), r["hostCalls"].as_u64().unwrap()) + }; s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); - let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + let small = cost(&mut s); // 3 objects doubled 11 times: 6,144. s.execute("select.all", &json!({})).unwrap(); for _ in 0..11 { @@ -2318,11 +2530,39 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { s.execute("select.all", &json!({})).unwrap(); } s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); - crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); - let large = run(&mut s, edits); + assert_eq!(small, cost(&mut s)); +} + +/// Building a collection's list again after an edit counts the objects it lists against the +/// run's allowance, so a loop that edits and reads `pageItems`, `pathItems` or `textFrames` in a +/// large document ends with the limit instead of walking the document each time for nothing. +#[test] +fn rebuilding_a_collection_after_an_edit_counts_against_the_run() { + let (mut s, a, _) = doc(); + let source = |list: &str| { + format!("var d = app.activeDocument, it = d.pageItems[0]; for (var i = 0; i < 40; i++) {{ it.opacity = 50 + i % 2; d.{list}.length; }}") + }; + let lists = ["pageItems", "pathItems", "textFrames"]; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let small: Vec = lists.iter().map(|l| run(&mut s, &source(l)).is_ok()).collect(); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); - let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); - assert_eq!(small, large); + assert_eq!(small, vec![true; 3], "a small document stays under 1 MiB"); + // 2 objects doubled 11 times: 4,096, a list of 64 KiB each time it is built again. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + // Nothing selected, so putting the selection back after each edit passes no list of ids. + s.execute("select.none", &json!({})).unwrap(); + for list in lists { + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let r = run(&mut s, &source(list)); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("{list}: 40 lists of 4,096 objects stayed under 1 MiB: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data to and from commands"), "{list}: {e}"); + } } /// A collection read with a name gives what `getByName` gives, and throws as it does for no match. @@ -2340,6 +2580,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() { vc.log(m);", ); assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); + // A name the collection inherits is not looked up as an object's name when it is assigned. + let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);"); + assert_eq!(out, vec![json!(1)]); } /// A collection read with a name that is the text of a number but not an array index, such as `-1` diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 87f1c4f9ab..8988c042eb 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() { assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); } +#[test] +fn path_changes_refuse_paths_on_a_locked_artboard() { + let (mut s, a, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + // Points (waiting and written at once), paint, stroke and a transform. + for change in [ + "p.closed = false;", + "p.pathPoints[0].anchor = [1, 2];", + "p.setEntirePath([[0, 0], [10, 10]]);", + "p.filled = false;", + "p.strokeWidth = 7;", + "p.translate(5, 5);", + ] { + let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); + assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); + } + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); + // A value the path has changes nothing and does not throw, and the path changes once the + // artboard is unlocked. + log(&mut s, "app.activeDocument.pathItems[0].closed = true;"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;"); + assert_ne!(art(&s), before); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1e2823aaa4..b5d7fe7ded 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1020,6 +1020,7 @@ fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() { /// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias` /// set `error` and change nothing. #[cfg(not(unix))] +// test-lint: allow never-run Windows only (not Unix); CI runs tests on Linux and FreeBSD #[test] fn script_file_hidden_and_aliases_are_refused_off_unix() { let base = folder("hiddenoff"); @@ -1637,6 +1638,7 @@ fn script_file_rename_does_not_take_the_settings_folders_name() { /// Where case does not matter, a folder named in another case is still the folder that holds the /// settings folder, or the settings folder itself: it is not renamed or removed. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { let base = folder("moveupcase"); @@ -1660,6 +1662,7 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() /// Where case does not matter, a folder renamed under its name in another case still moves the open /// objects of the files in it: changes are written under the new name, not lost at the old one. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { let base = folder("renamecase"); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 45d5a22417..c9cb73e774 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -2,9 +2,11 @@ //! specifiers and paths, the run's limits, and errors at the file they are in. use std::path::{Path, PathBuf}; +use std::time::Duration; use serde_json::{Value, json}; +use crate::script::folder::Clock; use crate::*; /// A fresh folder for test `name`, with a `main` folder inside it for the script. @@ -217,8 +219,11 @@ fn script_module_is_listed_and_taken_by_path() { write(&root.join("tool.mjs"), "export var a = 1;"); let mut s = Session::new(); s.attach_scripts_dir(root.clone()); + // The listing's time limit is checked against a clock that does not move. + s.set_script_listing_clock(Clock::Fixed(Duration::ZERO)); let listed = s.execute("script.listInstalled", &json!({})).unwrap(); assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}])); + assert_eq!(listed["truncated"], false); // A script given as text is not a module, whatever its name. let mut s = Session::new(); let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"})); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs new file mode 100644 index 0000000000..1c15b3e9f0 --- /dev/null +++ b/crates/engine/src/tests/script_print.rs @@ -0,0 +1,748 @@ +//! Printing from a script: `Document.print` with `PrintOptions` and its option classes, +//! `app.printPresetsList`, `app.PPDFileList`, and the checks every option and the file go through. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers}; +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A test's folder, removed when the test ends, a failed assertion included. +struct Workspace(PathBuf); + +impl std::ops::Deref for Workspace { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +impl AsRef for Workspace { + fn as_ref(&self) -> &Path { + &self.0 + } +} + +impl Drop for Workspace { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> Workspace { + let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + Workspace(std::fs::canonicalize(&base).unwrap()) +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a +/// 300 × 200 document of two artboards holding a rectangle. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +fn pages(path: &Path) -> Vec<(f64, f64)> { + let info = vectorcraft_pdf::info(&std::fs::read(path).unwrap(), None).unwrap(); + info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect() +} + +#[test] +fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { + let base = folder("happy"); + let mut s = session(&base); + s.execute("print.setup", &json!({"settings": {"collate": true, "marks": {"trim": true}}})).unwrap(); + let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone(); + let undo = s.active().unwrap().history.undo.len(); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, doc = app.activeDocument;\n\ + var o = new PrintOptions(), j = new PrintJobOptions();\n\ + vc.log([o.typename, j.typename, j.copies, j.collate, j.printAllArtboards, j.designation, o.coordinateOptions.typename]);\n\ + o.jobOptions = j; j.copies = 2; j.file = new File(dir + '/a.pdf');\n\ + j.copies = 3; vc.log([o.jobOptions.copies, j.collate]);\n\ + doc.print(o);\n\ + var back = o.jobOptions.file; j.file = back; vc.log([back instanceof File, back.name]);\n\ + j.printAllArtboards = false; j.artboardRange = '2'; j.copies = 1; j.file = new File(dir + '/b.pdf');\n\ + o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ + o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\ + doc.print(o);\n\ + j.file = new File(dir + '/c.ps'); doc.print(o);\n\ + o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\ + doc.print(o);\n\ + vc.log([app.printPresetsList[0], app.PPDFileList.length]);" + ), + ); + let expected = + json!(["PrintOptions", "PrintJobOptions", 1, false, true, "PrintArtworkDesignation.VISIBLEPRINTABLELAYERS", "PrintCoordinateOptions"]); + assert_eq!(out[0], expected, "a new option object reads as its help page's defaults"); + assert_eq!(out[1], json!([3, false]), "a change after the assignment is read through the PrintOptions"); + assert_eq!(out[2], json!([true, "a.pdf"]), "jobOptions.file reads back as a File"); + assert_eq!(out[3], json!(["[Default]", 0])); + assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies"); + assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4"); + let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap(); + assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]); + let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap(); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); + // The commands stay closed to vc.run, before and after a print. + for case in [ + "vc.run('file.print', {});", + "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/d.pdf'); app.activeDocument.print(o); vc.run('file.print', {});", + "vc.run('print.setup', {settings: {copies: 5}});", + ] { + let e = failure(&mut s, &base, case); + assert!(e.contains("a script cannot run"), "{case}: {e}"); + } + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved); + let _ = std::fs::remove_dir_all(base); +} + +/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to +/// a printer and `app.printerList` throw, and nothing is prepared. +#[test] +fn print_without_a_file_does_not_print() { + let base = folder("no-file"); + let mut s = session(&base); + for case in [ + "app.activeDocument.print();", + "app.activeDocument.print(new PrintOptions());", + "var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);", + "var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);", + ] { + let e = failure(&mut s, &base, case); + assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}"); + } + let e = failure(&mut s, &base, "app.printerList;"); + assert!(e.contains("Application.printerList is not available here"), "{e}"); + assert!(!s.script_prints_waiting()); + let _ = std::fs::remove_dir_all(base); +} + +/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would +/// read as more than a name. +const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p"; + +fn printers() -> Printers { + Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false) +} + +/// The PDF pages a prepared job holds. +fn job_pages(job: &PreparedPrint) -> usize { + vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len() +} + +/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them, +/// without names that are empty, too long, hold a control character or repeat; the list is the +/// run's own, needs an open document, and its objects go stale after the run. +#[test] +fn printer_list_is_the_bounded_list_the_frontend_gave() { + let base = folder("printer-list"); + let mut s = session(&base); + let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect(); + list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true)); + list.insert(1, ("Bad\nName".into(), false)); + list.insert(2, (String::new(), false)); + list.insert(3, ("Printer 5".into(), false)); + let snapshot = Printers::new(list, false); + assert_eq!(snapshot.names().len(), MAX_PRINTERS); + assert_eq!(snapshot.default_name(), Some("Printer 1")); + // A default listed after the first 256 takes the last place, and a repeated name keeps a later + // default mark without a second entry. + let late = Printers::new((0..300).map(|i| (format!("Q{i}"), i == 280)), false); + let names = late.names(); + assert_eq!((names.len(), late.default_name(), names[254].as_str(), names[255].as_str()), (MAX_PRINTERS, Some("Q280"), "Q254", "Q280")); + let repeat = Printers::new([("A".to_string(), false), ("B".to_string(), false), ("A".to_string(), true)], false); + assert_eq!((repeat.names(), repeat.default_name()), (&["A".to_string(), "B".to_string()][..], Some("A"))); + s.script_printers = Some(snapshot); + let out = logged( + &mut s, + &base, + "#targetengine keep\nvar l = app.printerList; held = l[0];\n\ + vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\ + try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\ + try { l[0].printerInfo; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"])); + assert_eq!(out[1], json!("Printer 5"), "name is read-only"); + assert_eq!(out[2], json!("Printer.printerInfo is not available yet")); + // The next run has no list unless the frontend gives one again. + let e = failure(&mut s, &base, "app.printerList;"); + assert!(e.contains("Application.printerList is not available here"), "{e}"); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale printer"), "{e}"); + s.script_printers = Some(printers()); + assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME)); + // With no document open there is no list. + let mut empty = Session::new(); + empty.attach_script_data(base.join("settings/Script Data")); + empty.script_printers = Some(printers()); + let e = failure(&mut empty, &base, "app.printerList;"); + assert!(e.contains("Application.printerList needs an open document"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one, +/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend +/// to take. A name is matched exactly, whatever characters it holds. +#[test] +fn print_to_a_printer_holds_the_job_until_the_run_ends() { + let base = folder("prepared"); + let mut s = session(&base); + s.script_printers = Some(printers()); + let name = serde_json::to_string(ODD_NAME).unwrap(); + let report = run( + &mut s, + &base, + &format!( + "var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\ + app.activeDocument.print(o);\n\ + vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\ + app.activeDocument.print();" + ), + ) + .unwrap(); + assert_eq!(report["prints"], 2, "{report}"); + assert!(s.script_prints_waiting()); + let title = s.active().unwrap().title(); + let jobs = s.take_script_prints(); + assert!(!s.script_prints_waiting()); + assert_eq!(jobs.len(), 2); + assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies"); + assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer"); + assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF"))); + // Each job holds the document as it was when print was called: one copy of the second job has + // the rectangle the script added after the first job, and the first job's two copies do not. + let paths = |job: &PreparedPrint| { + let mut n = 0; + vectorcraft_pdf::import(&job.pdf).unwrap().walk(|c| n += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }))); + n + }; + assert_eq!(paths(&jobs[0]) % 2, 0, "two equal copies"); + assert_eq!(paths(&jobs[0]) / 2 + 1, paths(&jobs[1]), "the second job has the added rectangle"); + assert!(s.take_script_prints().is_empty(), "a job is taken once"); + let _ = std::fs::remove_dir_all(base); +} + +/// A run that throws, runs out of fuel or ends at a failed command keeps no job. +#[test] +fn a_run_that_fails_keeps_no_print_job() { + let base = folder("rollback"); + let mut s = session(&base); + let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len); + for case in [ + "app.activeDocument.print(); throw new Error('late');", + "app.activeDocument.print(); vc.run('no.such.command', {});", + "app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();", + ] { + s.script_printers = Some(printers()); + failure(&mut s, &base, case); + assert!(!s.script_prints_waiting(), "{case}"); + } + s.script_printers = Some(printers()); + let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000})); + assert!(stopped.is_err()); + assert!(s.take_script_prints().is_empty()); + assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects); + let _ = std::fs::remove_dir_all(base); +} + +/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or +/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is +/// prepared; a file wins over a printer name. +#[test] +fn print_to_a_printer_refuses_what_it_cannot_send() { + let base = folder("refuse"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let cases = [ + ("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"), + ("o.printerName = 'Offic';", "names no installed printer: Offic"), + ("o.printerName = ' Office';", "names no installed printer: Office"), + ("o.printerName = 'Office\\n';", "names no installed printer"), + ("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"), + ("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"), + ("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"), + ("o.printPreset = 'Nope';", "printPreset names no print preset"), + ]; + for (case, part) in cases { + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);")); + assert!(e.contains(part), "{case}: {e}"); + assert!(!s.script_prints_waiting(), "{case}"); + } + // A job past the sheet limit is refused before it is composed. + s.script_printers = Some(printers()); + failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);"); + let report = s.script_report().unwrap(); + let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect(); + assert_eq!(ran, ["file.print"], "{report}"); + s.script_printers = Some(Printers::new([("Office".to_string(), false)], false)); + let e = failure(&mut s, &base, "app.activeDocument.print();"); + assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}"); + // Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken. + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "app.activeDocument.print();"); + assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}"); + assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept"); + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + assert_eq!(s.take_script_prints().len(), 1); + // A file wins over the printer name. + s.script_printers = Some(printers()); + let file = quoted(&dir.join("f.pdf")); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);" + ), + ); + assert!(dir.join("f.pdf").exists()); + assert!(!s.script_prints_waiting()); + let _ = std::fs::remove_dir_all(base); +} + +/// The pages of a job for a printer are counted from the art as it prints, artboard backgrounds +/// included, as `file.print` lays it out: an artboard that holds only its background prints with +/// `skipBlank`, and counts toward the sheet limit. +#[test] +fn print_to_a_printer_counts_the_pages_of_the_art_as_it_prints() { + let base = folder("backgrounds"); + let mut s = session(&base); + s.execute("artboard.setProps", &json!({"index": 1, "color": "#ff0000"})).unwrap(); + s.execute("print.setup", &json!({"settings": {"skipBlank": true, "artboards": "range", "range": "2"}})).unwrap(); + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + let jobs = s.take_script_prints(); + assert_eq!(jobs.iter().map(|j| (j.sheets, job_pages(j))).collect::>(), [(1, 1)], "the background prints"); + s.execute("print.setup", &json!({"settings": {"artboards": "all"}})).unwrap(); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 51; app.activeDocument.print(o);"); + assert!(e.contains("this job has 102"), "both artboards print: {e}"); + assert!(!s.script_prints_waiting()); + let _ = std::fs::remove_dir_all(base); +} + +/// `file.print`'s `maxPages` composes nothing for a longer job, and only after the other params are +/// checked. +#[test] +fn file_print_max_pages_composes_only_what_fits() { + let base = folder("max-pages"); + let mut s = session(&base); + let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}"); + let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r["dataBase64"].is_string()), (&json!(6), true)); + for bad in [ + json!({"maxPages": 0, "format": "postscript", "level": 1}), + json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}), + json!({"maxPages": -1}), + json!({"maxPages": "2"}), + json!({"maxPages": null}), + ] { + assert!(s.execute("file.print", &bad).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Bad values throw when they are assigned, and nothing prints. +#[test] +fn print_options_refuse_bad_values() { + let base = folder("bad"); + let mut s = session(&base); + let cases = [ + ("j.copies = 0;", "RangeError", "copies must be a whole number from 1 to 999"), + ("j.copies = NaN;", "TypeError", "copies"), + ("j.copies = 1e12;", "RangeError", "copies must be a whole number"), + ("j.copies = 1.5;", "RangeError", "copies must be a whole number"), + ("j.copies = '2';", "TypeError", "copies must be a number"), + ("j.collate = 1;", "TypeError", "collate must be true or false"), + ("c.horizontalScale = NaN;", "TypeError", "horizontalScale"), + ("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"), + ("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"), + ("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"), + ("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"), + ("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"), + ("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"), + ("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"), + ("j.file = {};", "TypeError", "file must be a File"), + ("o.jobOptions = new PrintCoordinateOptions();", "TypeError", "jobOptions must be a PrintJobOptions"), + ("o.jobOptions = {copies: 2};", "TypeError", "jobOptions must be a PrintJobOptions"), + ("o.printPreset = new Array(5000).join('x');", "RangeError", "printPreset is too long"), + ("app.activeDocument.print({jobOptions: j});", "TypeError", "print's options must be a PrintOptions object"), + ("app.activeDocument.print(j);", "TypeError", "print's options must be a PrintOptions object"), + ]; + let prefix = "var o = new PrintOptions(), j = o.jobOptions, c = o.coordinateOptions, m = o.pageMarksOptions;"; + for (case, kind, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case}")); + assert!(e.contains(kind) && e.contains(part), "{case}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Options that `file.print` cannot honor throw instead of being dropped. +#[test] +fn options_that_are_not_available_throw() { + let base = folder("later"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let cases = [ + ("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"), + ("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"), + ("j.name = 'Job';", "PrintJobOptions.name is not available yet"), + ("j.printArea = PrintingBounds.ARTWORKBOUNDS;", "PrintingBounds.ARTWORKBOUNDS is not available yet"), + ("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.INRIPSEPARATION;", "INRIPSEPARATION is not available yet"), + ("o.colorManagementOptions.colorProfileMode = PrintColorProfile.PRINTERPROFILE;", "PRINTERPROFILE is not available yet"), + ("o.colorSeparationOptions.inkList = [];", "PrintColorSeparationOptions.inkList is not available yet"), + ("o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADCOMPLETE;", "PrintFontOptions.downloadFonts is not available yet"), + ("o.flattenerOptions.rasterizationResolution = 600;", "PrintFlattenerOptions.rasterizationResolution is not available yet"), + ("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"), + ("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"), + ("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"), + ("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"), + ("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"), + ( + &format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"), + "horizontalScale above 1000 is not available yet", + ), + ]; + let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;"; + for (case, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case}")); + assert!(e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // With Fit to Page on, the scale factors are not used, so a factor above 1000 does not stop the job. + let out = logged( + &mut s, + &base, + &format!( + "{prefix} {file} var c = o.coordinateOptions; c.horizontalScale = 2000; c.verticalScale = 2000; c.fitToPage = true;\ + app.activeDocument.print(o); vc.log(true);" + ), + ); + assert_eq!(out, json!([true])); + assert!(dir.join("x.pdf").exists(), "the fitted job printed"); + let _ = std::fs::remove_dir_all(base); +} + +/// A panic while `print` has the fence open for `file.print` closes it again for the next run. +#[test] +fn a_panic_while_printing_leaves_the_fence_closed() { + let base = folder("panic-unfenced"); + let mut s = session(&base); + let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);"; + crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true)); + let r = run(&mut s, &base, print); + crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false)); + let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}"); + let e = failure(&mut s, &base, "vc.run('file.print', {});"); + assert!(e.contains("a script cannot run"), "{e}"); +} + +#[test] +fn print_writes_only_where_the_script_may() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let grants = base.join("settings/Script Grants.json"); + std::fs::write(&grants, "{}").unwrap(); + for target in [base.join("outside/x.pdf"), grants.clone(), dir.clone()] { + let case = + format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&target)); + let e = failure(&mut s, &base, &case); + assert!(e.contains("Script file"), "{case}: {e}"); + if target != dir { + assert!(e.contains(DENIED), "{case}: {e}"); + } + } + assert!(!base.join("outside/x.pdf").exists()); + assert_eq!(std::fs::read_to_string(&grants).unwrap(), "{}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A print to a file a `File` object holds open for writing throws, so the object's bytes written at +/// the end of the run do not replace the printed file. +#[test] +fn print_does_not_write_a_file_open_for_writing() { + let base = folder("openhandle"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let p = quoted(&dir.join("x.pdf")); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var w = new File({p}); w.open('w'); w.write('pending');\nvar o = new PrintOptions(); o.jobOptions.file = new File({p});\ntry {{ app.activeDocument.print(o); vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{log}"); + assert_eq!(std::fs::read_to_string(dir.join("x.pdf")).unwrap(), "pending", "the File's own bytes"); + let _ = std::fs::remove_dir_all(base); +} + +/// One assigned scale factor leaves the other at the document's saved value. +#[test] +fn one_assigned_scale_factor_keeps_the_saved_other() { + let base = folder("scale"); + let mut s = session(&base); + let common = json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1"}); + let mut saved = common.clone(); + saved["scale"] = json!({"width": 100, "height": 500, "linked": false}); + s.execute("print.setup", &json!({"settings": saved})).unwrap(); + let dir = data_folder(&mut s, &base); + let mut expected = common; + expected["scaling"] = json!("tileFull"); + expected["scale"] = json!({"width": 400, "height": 500, "linked": false}); + let want = s.execute("file.print", &json!({"settings": expected, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.coordinateOptions.horizontalScale = 400; o.coordinateOptions.tiling = PrintTiling.TILEFULLPAGES;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("got.pdf")) + ), + ); + let got = pages(&dir.join("got.pdf")); + assert_eq!(got.len() as u64, want["pages"].as_u64().unwrap(), "the saved vertical scale of 500% is kept"); + assert!(got.len() >= 4, "1200 by 1000 pt of art tiles over at least four letter pages: {got:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over +/// saved settings that ignore the artboards, and two scale factors that differ by any amount print +/// unlinked. +#[test] +fn assigned_job_and_scale_options_apply_over_the_saved_settings() { + let base = folder("over-saved"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let print = |s: &mut Session, name: &str, body: &str| { + let file = quoted(&dir.join(name)); + logged( + s, + &base, + &format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"), + ); + pages(&dir.join(name)).len() + }; + s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap(); + assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range"); + assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one"); + s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap(); + assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page"); + assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints"); + assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards"); + let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';"; + assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range"); + let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;"; + assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked"); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the +/// granted folder leads to. +#[cfg(unix)] +#[test] +fn the_format_follows_the_name_the_script_gives() { + let base = folder("format-name"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("proof.pdf"), "old").unwrap(); + std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", + quoted(&dir.join("proof.ps")) + ), + ); + let written = std::fs::read(dir.join("proof.pdf")).unwrap(); + assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)])); + let _ = std::fs::remove_dir_all(base); +} + +/// Artboard ranges the document does not hold and preset names that are not presets, such as +/// paths, throw before anything is written. +#[test] +fn print_refuses_ranges_and_preset_names_it_cannot_honor() { + let base = folder("names"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let cases = [ + ("j.printAllArtboards = false; j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"), + ("j.printAllArtboards = false; j.artboardRange = '0-1';", "RangeError", "artboardRange"), + ("j.printAllArtboards = false; j.artboardRange = '../../outside';", "RangeError", "artboardRange"), + ("j.printAllArtboards = false; j.artboardRange = '2-1';", "RangeError", "artboardRange"), + ("j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"), + ("o.printPreset = 'Office';", "Error", "printPreset names no print preset: Office"), + (&format!("o.printPreset = {};", quoted(&base.join("settings/Script Grants.json"))), "Error", "printPreset names no print preset"), + ("o.printPreset = '../../preset';", "Error", "printPreset names no print preset"), + ("o.flattenerPreset = '/etc/passwd';", "Error", "flattenerPreset names no flattener preset"), + (&format!("o.flattenerPreset = {};", quoted(&base.join("outside/f.xml"))), "Error", "flattenerPreset names no flattener preset"), + ]; + let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {file}"); + for (case, kind, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);")); + assert!(e.contains(kind) && e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // The names the lists give print, in any case. + logged(&mut s, &base, &format!("{prefix} o.printPreset = '[default]'; o.flattenerPreset = 'high resolution'; app.activeDocument.print(o);")); + assert!(dir.join("x.pdf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A color profile, a paper or a preset name that is empty, path-shaped, holds a control character +/// or is not on its list throws before anything is written; a listed name in any case prints. +#[test] +fn print_refuses_profile_paper_and_blank_preset_names() { + let base = folder("profile-paper"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let profile = "PrintColorManagementOptions.name names no color profile"; + let paper = "PrintPaperOptions.name names no paper"; + let cases = [ + ("c.name = '../sRGB IEC61966-2.1';", profile), + ("c.name = 'C:/Windows/System32/spool/drivers/color/sRGB IEC61966-2.1';", profile), + ("c.name = '\\\\\\\\server\\\\share\\\\cmyk.icc';", profile), + ("c.name = 'No Such Profile';", profile), + ("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile), + ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), + ("p.name = '../letter';", paper), + ("p.name = 'let\\u0007ter';", paper), + ("p.name = '\\tA4\\n';", paper), + ("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"), + ("p.name = 'Office Tray 2';", paper), + ("p.name = '';", "PrintPaperOptions.name must name a paper"), + ("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"), + ("o.flattenerPreset = ' ';", "PrintOptions.flattenerPreset must name a flattener preset"), + ("o.flattenerPreset = '';", "PrintOptions.flattenerPreset must name a flattener preset"), + ("o.printPreset = ' ';", "PrintOptions.printPreset must name a print preset"), + ]; + let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions, c = o.colorManagementOptions, p = o.paperOptions; {file}"); + for (case, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);")); + assert!(e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // Listed names print in any case and with spaces around them. + logged( + &mut s, + &base, + &format!( + "{prefix} c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; c.name = 'srgb iec61966-2.1'; p.name = ' A4 ';\n\ + o.printPreset = ' [Default] '; o.flattenerPreset = ' High Resolution '; app.activeDocument.print(o);" + ), + ); + let sizes = pages(&dir.join("x.pdf")); + assert!(!sizes.is_empty() && sizes.iter().all(|&(w, h)| [(595.0, 842.0), (842.0, 595.0)].contains(&(w, h))), "A4: {sizes:?}"); + // A custom paper takes the assigned size. + let custom = format!( + "Folder.userData; var o = new PrintOptions(), p = o.paperOptions; o.jobOptions.file = new File({});\n\ + p.name = 'Custom'; p.width = 360; p.height = 504; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("custom.pdf")) + ); + logged(&mut s, &base, &custom); + let sizes = pages(&dir.join("custom.pdf")); + assert!(!sizes.is_empty() && sizes.iter().all(|&size| size == (360.0, 504.0)), "custom: {sizes:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Each warning `file.print` gives goes to the Script Console. +#[test] +fn print_writes_its_warnings_to_the_script_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let settings = json!({"color": {"profile": "sRGB IEC61966-2.1"}}); + let want = + s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": dir.join("want.ps").to_string_lossy()})).unwrap(); + let warnings: Vec = want["warnings"].as_array().unwrap().iter().map(|w| format!("Document.print: {}", w.as_str().unwrap())).collect(); + assert!(warnings.iter().any(|w| w.contains("printer profile")), "{want}"); + let report = run( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.colorManagementOptions.name = 'sRGB IEC61966-2.1'; o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("got.ps")) + ), + ) + .unwrap(); + assert_eq!(report["console"]["lines"], json!(warnings)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_objects_are_bounded_and_go_stale_after_their_run() { + let base = folder("bounds"); + let mut s = session(&base); + let e = failure(&mut s, &base, "for (var i = 0; i < 1000; i++) new PrintJobOptions();"); + assert!(e.contains("RangeError") && e.contains("at most 256 print option objects"), "{e}"); + let e = failure(&mut s, &base, "var o = new PrintOptions(); for (var i = 0; i < 1000; i++) o.jobOptions = new PrintJobOptions();"); + assert!(e.contains("at most 256"), "{e}"); + // A named engine keeps its globals, but an option object from an earlier run is stale. + run(&mut s, &base, "#targetengine keep\nvar held = new PrintOptions();").unwrap(); + let e = failure(&mut s, &base, "#targetengine keep\nnew PrintOptions(); held.printPreset;"); + assert!(e.contains("Stale print options"), "{e}"); + let e = failure(&mut s, &base, "#targetengine keep\napp.activeDocument.print(held);"); + assert!(e.contains("Stale print options"), "{e}"); + let e = failure(&mut s, &base, "#targetengine keep\nvar o = new PrintOptions(); o.jobOptions = held.jobOptions;"); + assert!(e.contains("Stale print options"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 8fd3e8c8fe..fe56754ca3 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -88,10 +88,10 @@ fn a_run_is_one_undo_step_in_each_document_it_changed() { #[test] fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() { + let dir = fresh_folder("noop"); for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] { let mut s = two_docs(); - s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()})) - .unwrap(); + s.execute("document.save", &json!({"path": dir.join("noop.svg").to_string_lossy()})).unwrap(); let before = state(&s); let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); let revisions_before = revisions(&s); @@ -183,6 +183,11 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw new ReferenceError('Window is not defined');", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: activeDocument is not defined';", "thrown", "ReferenceError: activeDocument is not defined", "script"), + ("throw new ReferenceError('activeDocument is not defined');", "thrown", "ReferenceError: activeDocument is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -266,9 +271,7 @@ fn bad_parameters_are_refused_before_anything_runs() { #[test] fn files_are_checked_before_they_are_read() { - let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir = fresh_folder("checked"); let write = |name: &str, bytes: &[u8]| { let p = dir.join(name); std::fs::write(&p, bytes).unwrap(); @@ -296,7 +299,6 @@ fn files_are_checked_before_they_are_read() { assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3])); std::fs::create_dir_all(dir.join("folder.js")).unwrap(); assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,7 +343,6 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); assert!(e.contains("SyntaxError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -367,7 +368,6 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri assert_eq!(legacy["log"], json!([false]), "{legacy}"); // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -390,7 +390,6 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() } // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -417,7 +416,6 @@ fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); assert!(e.contains("TypeError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -451,7 +449,6 @@ fn every_script_reads_e4x_and_has_the_xml_objects() { s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap(); let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('2').toString());"))).unwrap(); assert_eq!(later["log"], json!(["2"]), "{later}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -474,15 +471,11 @@ fn a_js_script_defines_classes_and_a_jsx_script_cannot() { assert!(e.contains("SyntaxError"), "{name}: {e}"); } assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } -/// A new empty folder for test `name`. -fn fresh_folder(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir +/// A new empty folder for test `name`, removed when dropped, also when the test fails. +fn fresh_folder(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("script-run-{name}")) } /// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder @@ -530,7 +523,6 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); assert!(path.exists()); assert_eq!(r["written"], json!([p]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -544,7 +536,6 @@ fn an_export_that_fails_names_no_file() { assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The commands a script runs read and write only where its `File` and `Folder` objects may (its @@ -594,7 +585,6 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let r = run(&mut s, &call("document.save", &own)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); assert!(own.exists()); - let _ = std::fs::remove_dir_all(&dir); } /// The color at the middle of the PNG at `path`. @@ -656,7 +646,6 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); - let _ = std::fs::remove_dir_all(&dir); } /// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate @@ -674,7 +663,8 @@ fn tried(id: &str, params: &str) -> String { #[test] fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { use crate::tests_links::{RED, open, place, png, save, session, write}; - let art = fresh_folder("gate-linked-runs").join("art"); + let root = fresh_folder("gate-linked-runs"); + let art = root.join("art"); std::fs::create_dir_all(&art).unwrap(); let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); @@ -704,7 +694,6 @@ fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() log.push(later["log"][0].clone()); assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); - let _ = std::fs::remove_dir_all(art.parent().unwrap()); } /// A data set value a script gives a document, and a document a script opens, let no later run @@ -741,7 +730,6 @@ fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { s.execute("document.save", &json!({"path": mine})).unwrap(); let saved = run(&mut s, &read_secret).unwrap(); assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); - let _ = std::fs::remove_dir_all(&dir); } /// A save the person started before a script's command changed the document, and that finishes @@ -766,7 +754,6 @@ fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { job.complete(&mut s, uid); let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); assert_eq!(r["log"], json!(["denied"]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// A command a script runs does not save into the app's own libraries; the same command run @@ -784,7 +771,6 @@ fn a_scripts_commands_do_not_save_into_the_apps_libraries() { assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -867,7 +853,6 @@ fn an_abandoned_run_reports_the_files_it_wrote() { let report = s.script_report().unwrap(); assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); assert!(s.script_failure_text().unwrap().contains(&p)); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1457,15 +1442,13 @@ fn a_file_saved_before_a_failure_stays_written_and_is_named() { assert!(e.contains(&p), "{e}"); assert_eq!(s.script_report().unwrap()["written"], json!([p])); assert_eq!(state(&s), before, "the document does not keep the new path"); - let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope /// the frames that advance it run in. #[test] fn a_framed_run_keeps_the_file_access_scope_it_started_in() { - let dir = std::env::temp_dir().join(format!("vc-script-scope-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = fresh_folder("scope"); let (allowed, outside) = (dir.join("allowed"), dir.join("outside")); std::fs::create_dir_all(&allowed).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -1492,13 +1475,12 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_committed_run_exports_what_it_drew() { - let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("export"); + let path = dir.join("export.svg"); let p = path.to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); @@ -1509,7 +1491,6 @@ fn a_committed_run_exports_what_it_drew() { assert_eq!(svg.matches(" PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +#[test] +fn save_as_export_file_and_open_write_and_read_where_the_script_may() { + let base = folder("happy"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + d.saveAs(new File(dir + '/a.svg'));\n\ + var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ + o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.pDFXStandardDescription = undefined;\n\ + o.colorCompression = 'CompressionQuality.None';\n\ + d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ + var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\ + d.exportFile(new File(dir + '/c'), ExportType.PNG24, p);\n\ + d.exportFile(new File(dir + '/e.JPG'), ExportType.JPEG);\n\ + var v = new ExportOptionsSVG(); v.compressed = true; v.coordinatePrecision = 2;\n\ + d.exportFile(new File(dir + '/f'), ExportType.SVG, v); vc.log(d.name);\n\ + var g = app.open(new File(dir + '/a.svg'));\n\ + vc.log([g.typename, app.documents.length, app.activeDocument.name === g.name, g.name]);\n\ + var u = [app.userInteractionLevel]; app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; u.push(app.userInteractionLevel); vc.log(u);" + ), + ); + assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true])); + assert_eq!(out[1], json!("b.pdf"), "saveAs gives the document the new file"); + assert_eq!(out[2], json!("b.pdf"), "exportFile leaves the document's file as it is"); + assert_eq!(out[3], json!(["Document", 2, true, "a.svg"])); + assert_eq!(out[4], json!(["UserInteractionLevel.DISPLAYALERTS", "UserInteractionLevel.DONTDISPLAYALERTS"])); + assert!(std::fs::read_to_string(dir.join("a.svg")).unwrap().contains("").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link))); + assert_eq!(out, json!([["drawing.svg", "drawing.svg"]])); + assert_eq!(s.active().unwrap().format, "svg"); + let _ = std::fs::remove_dir_all(base); +} + +/// Without options, a save or export writes what an untouched new options object of its class gives. +#[test] +fn omitted_options_are_a_new_options_objects_defaults() { + let base = folder("defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + d.exportFile(new File(dir + '/j1'), ExportType.JPEG);\n\ + d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\ + d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\ + d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\ + d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\ + d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\ + d.saveAs(new File(dir + '/a1.pdf'));\n\ + d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());" + ), + ); + for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] { + assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ"); + } + for name in ["a1.pdf", "a2.pdf"] { + let pdf = std::fs::read(dir.join(name)).unwrap(); + assert!(pdf.starts_with(b"%PDF-1.4"), "{name}: PDFCompatibility.ACROBAT5 is PDF 1.4, {:?}", String::from_utf8_lossy(&pdf[..8])); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or +/// opened, so no file with a lossy copy of the name is touched. +#[cfg(unix)] +#[test] +fn script_file_commands_refuse_non_utf8_resolved_paths() { + use std::os::unix::ffi::OsStringExt; + + let base = folder("non-utf8-target"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let original = dir.join("original.vectorcraft"); + s.execute("file.saveAs", &json!({"path": original.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec())); + // A file system that refuses such a name has nothing to refuse. + if std::fs::write(&target, &bytes).is_err() { + let _ = std::fs::remove_dir_all(base); + return; + } + let link = dir.join("alias.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let lossy = PathBuf::from(target.to_string_lossy().into_owned()); + std::fs::write(&lossy, &bytes).unwrap(); + for call in ["app.activeDocument.saveAs(f);", "app.activeDocument.exportFile(f, ExportType.SVG);", "app.open(f);"] { + let alias = if call.contains("exportFile") { + let alias = dir.join("alias.svg"); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + alias + } else { + link.clone() + }; + let count = s.documents().len(); + let error = failure(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&alias))); + assert!(error.contains("Script file path is not valid UTF-8"), "{call}: {error}"); + assert_eq!(s.documents().len(), count); + assert_eq!(std::fs::read(&target).unwrap(), bytes); + assert_eq!(std::fs::read(&lossy).unwrap(), bytes); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Every enumeration an option keeps its default in is defined: the default member is accepted, and +/// another member of the same enumeration is refused as not available yet. +#[test] +fn kept_enum_options_accept_their_default_member() { + let base = folder("keptenums"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let file = |n: &str| format!("new File({})", quoted(&dir.join(n))); + let cases: &[(&str, &str, &str, &str)] = &[ + ("IllustratorSaveOptions", "flattenOutput", "OutputFlattening.PRESERVEAPPEARANCE", "OutputFlattening.PRESERVEPATHS"), + ("PDFSaveOptions", "colorCompression", "CompressionQuality.None", "CompressionQuality.ZIP8BIT"), + ("PDFSaveOptions", "colorConversionID", "ColorConversion.None", "ColorConversion.COLORCONVERSIONTODEST"), + ("PDFSaveOptions", "colorDestinationID", "ColorDestination.None", "ColorDestination.COLORDESTINATIONPROFILE"), + ("PDFSaveOptions", "colorDownsamplingMethod", "DownsampleMethod.NODOWNSAMPLE", "DownsampleMethod.SUBSAMPLE"), + ("PDFSaveOptions", "colorProfileID", "ColorProfile.None", "ColorProfile.INCLUDEALLPROFILE"), + ("PDFSaveOptions", "monochromeCompression", "MonochromeCompression.None", "MonochromeCompression.CCIT4"), + ("PDFSaveOptions", "pageMarksType", "PageMarksTypes.Roman", "PageMarksTypes.Japanese"), + ("PDFSaveOptions", "pDFAllowPrinting", "PDFPrintAllowedEnum.PRINT128HIGHRESOLUTION", "PDFPrintAllowedEnum.PRINT40NONE"), + ("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"), + ("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"), + ("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"), + ("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"), + ("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"), + ("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"), + ("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"), + ("ExportOptionsSVG", "fontType", "SVGFontType.CEFFONT", "SVGFontType.OUTLINEFONT"), + ]; + for (i, (class, key, default, other)) in cases.iter().enumerate() { + let call = |value: &str, n: String| { + let set = format!("var o = new {class}(); o.{key} = {value};"); + match *class { + "ExportOptionsSVG" => format!("{set} app.activeDocument.exportFile({}, ExportType.SVG, o);", file(&format!("{n}.svg"))), + "PDFSaveOptions" => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.pdf"))), + _ => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.ai"))), + } + }; + logged(&mut s, &base, &format!("Folder.userData; {}", call(default, format!("ok{i}")))); + let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}")))); + assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A raster export at 100% has one pixel per point, whatever the document's raster effects +/// resolution. +#[test] +fn a_raster_export_at_100_percent_has_a_pixel_per_point() { + let base = folder("rasterscale"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.activeDocument, o = new ExportOptionsPNG24(); o.artBoardClipping = true;\n\ + d.exportFile(new File(dir + '/a'), ExportType.PNG24, o);\n\ + var j = new ExportOptionsJPEG(); j.artBoardClipping = true; d.exportFile(new File(dir + '/b'), ExportType.JPEG, j);" + ), + ); + for name in ["a.png", "b.jpg"] { + let image = image::open(dir.join(name)).unwrap(); + assert_eq!((image.width(), image.height()), (200, 100), "{name}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and +/// an option the script changes applies over the preset. +#[test] +fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() { + let base = folder("preset"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.pDFPreset = 'High Quality Print'; d.saveAs(new File(dir + '/a.pdf'), o);\n\ + o.compatibility = PDFCompatibility.ACROBAT8; d.saveAs(new File(dir + '/b.pdf'), o);" + ), + ); + for (name, version) in [("a.pdf", b"%PDF-1.6"), ("b.pdf", b"%PDF-1.7")] { + let pdf = std::fs::read(dir.join(name)).unwrap(); + assert!(pdf.starts_with(version), "{name}: {:?}", String::from_utf8_lossy(&pdf[..8])); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A save that writes several files, such as an EPS with a file per artboard, writes none of them +/// when one may not be written. +#[test] +fn a_save_writes_nothing_when_one_of_its_files_is_refused() { + let base = folder("saveboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let save = format!("Folder.userData; vc.run('file.saveAs', {{path: {}, format: 'eps', useArtboards: true}});", quoted(&dir.join("a.eps"))); + logged(&mut s, &base, &save); + let central = dir.join("a.eps"); + let mut boards: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != central).collect(); + boards.sort(); + assert!(central.is_file() && boards.len() == 2, "the central file and a file per artboard: {boards:?}"); + let board = boards.pop().unwrap(); + std::fs::remove_file(¢ral).unwrap(); + let mut perms = std::fs::metadata(&board).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&board, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &save); + assert!(e.contains(DENIED), "{e}"); + assert!(!central.exists(), "the central file is not written when an artboard's file may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&board, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// When the writer a save is given does not check the file access itself, a save of several files +/// whose file access refuses one of them hands none of them to the writer. +#[test] +fn a_refused_file_stops_a_save_whose_writer_does_not_check() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + let base = folder("unchecked"); + let dir = base.join("outside"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let params = json!({"path": dir.join("a.eps").to_string_lossy(), "format": "eps", "useArtboards": true}); + let plan = save_plan(&s, SaveMode::SaveAs, ¶ms).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&dir), + documents: vec![], + held: vec![], + linked: Default::default(), + also: None, + }; + let (mut refused, mut written) = (None, vec![]); + let make_read_only = |paths: &[&str]| { + let last = paths.last().map(|p| p.to_string()).unwrap(); + std::fs::write(&last, b"").unwrap(); + let mut perms = std::fs::metadata(&last).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&last, perms).unwrap(); + refused = Some(last); + None + }; + let r = with_script_gate(gate, || { + job.write_unless(make_read_only, |p, _| { + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.is_err(), "{r:?}"); + let refused = refused.unwrap(); + assert_eq!(written, Vec::::new(), "no file went to the writer, the refused one ({refused}) included"); + let mut perms = std::fs::metadata(&refused).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&refused, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// Every path goes through the script's file grants, as a `File` opened for reading or writing. +#[test] +fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + std::fs::write(base.join("settings/Script Grants.json"), "{}").unwrap(); + std::fs::write(dir.join("kept.svg"), "kept").unwrap(); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let outside = quoted(&base.join("outside/x.svg")); + let grants = quoted(&base.join("settings/Script Grants.json")); + let kept = quoted(&dir.join("kept.svg")); + let secret = quoted(&base.join("outside/secret.svg")); + let cases = [ + format!("app.activeDocument.saveAs(new File({outside}));"), + format!("app.activeDocument.exportFile(new File({outside}), ExportType.PNG24);"), + format!("app.activeDocument.saveAs(new File({grants}));"), + format!("app.open(new File({secret}));"), + format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; app.activeDocument.saveAs(new File({outside}));"), + ]; + for case in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));")); + assert!(e.contains("Script file is read-only"), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir))); + assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}"); + assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}"); + assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists()); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None, "a refused save leaves the document's file as it is"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// The file of an open document is not written or read through a script method unless the +/// script's grants take it, though `vc.run`'s commands may use it. +#[test] +fn an_open_documents_file_is_not_saved_over_without_a_grant() { + let base = folder("opendoc"); + let mut s = session(&base); + let path = base.join("outside/open.svg"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let before = std::fs::read(&path).unwrap(); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes +/// written at the end of the run do not replace the saved document. +#[test] +fn a_file_open_for_writing_is_not_saved_over() { + let base = folder("openhandle"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (name, call) in + [("a.svg", "app.activeDocument.saveAs(new File(p));"), ("b.png", "app.activeDocument.exportFile(new File(p), ExportType.PNG24);")] + { + let p = quoted(&dir.join(name)); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var p = {p}, w = new File(p); w.open('w'); w.write('pending');\ntry {{ {call} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{name}: {log}"); + assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes"); + assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where +/// the script's grants allow, though it is an open document's file. +#[test] +fn open_reads_linked_files_only_where_the_script_may() { + let base = folder("linked"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.svg"); + std::fs::write(&linked, "").unwrap(); + s.execute("document.open", &json!({"path": linked.to_string_lossy()})).unwrap(); + assert!(s.active().unwrap().path.is_some(), "the linked file is an open document's file"); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + std::fs::write( + dir.join("page.svg"), + format!(""), + ) + .unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg")))); + assert_eq!(s.documents().len(), 2); + let ims = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((im.width, im.height, im.link.as_ref().map(|l| (l.modified.is_some(), l.hash.is_some())))); + } + }); + out + }; + let kinds = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind).chars().take(12).collect::())); + out + }; + assert_eq!(ims(&s), vec![(64, 64, Some((false, false)))], "the linked file is a placeholder: {:?}", kinds(&s)); + // Opened by the app, a copy of the file reads its image. + std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap(); + s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap(); + assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s)); + let _ = std::fs::remove_dir_all(base); +} + +/// An SVG export with `embedRasterImages` false writes the document's embedded image beside the +/// SVG, and when that file may not be written, the SVG is not written either. +#[test] +fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { + let base = folder("svgimages"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let export = + format!("Folder.userData; app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&dir.join("a.svg"))); + logged(&mut s, &base, &export); + let svg = dir.join("a.svg"); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let mut perms = std::fs::metadata(&image).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&image, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &export); + assert!(e.contains(DENIED), "{e}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&image, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// An export does not write a file it writes besides the one named, here an SVG's image, while a +/// `File` object holds it open for writing, and so writes nothing. +#[test] +fn an_svg_export_does_not_write_an_image_a_file_holds_open() { + let base = folder("svgheld"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let svg = dir.join("a.svg"); + let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&svg)); + logged(&mut s, &base, &format!("Folder.userData; {export}")); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var w = new File({}); w.open('w'); w.write('pending');\ntry {{ {export} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&image) + ), + ); + assert!(log[0].as_str().unwrap().contains(DENIED), "{log}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes"); + let _ = std::fs::remove_dir_all(base); +} + +/// A link inside a granted folder that leads out of it is followed and refused. +#[cfg(unix)] +#[test] +fn a_link_out_of_the_granted_folder_is_refused() { + let base = folder("link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::os::unix::fs::symlink(base.join("outside"), dir.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/target.svg"), dir.join("file.svg")).unwrap(); + std::fs::write(base.join("outside/read.svg"), "").unwrap(); + std::os::unix::fs::symlink(base.join("outside/read.svg"), dir.join("read.svg")).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for name in ["away/x.svg", "file.svg"] { + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir.join(name)))); + assert!(e.contains(DENIED), "{name}: {e}"); + } + let e = failure(&mut s, &base, &format!("app.open(new File({}));", quoted(&dir.join("read.svg")))); + assert!(e.contains(DENIED), "{e}"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// Without options, `saveAs` takes the format from the path the script names, not from the file a +/// link at that path leads to. +#[cfg(unix)] +#[test] +fn save_as_takes_the_format_of_the_named_path_through_a_link() { + let base = folder("link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("target.pdf"), "old").unwrap(); + std::os::unix::fs::symlink(dir.join("target.pdf"), dir.join("drawing.svg")).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg")))); + let written = std::fs::read(dir.join("target.pdf")).unwrap(); + assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF"); + assert!(String::from_utf8_lossy(&written).contains(" = vec![ + ("app.activeDocument.saveAs('x.svg');".into(), "saveAs needs a File"), + (format!("app.activeDocument.saveAs({{'\\u0000fileRef': {}}});", quoted(&dir.join("x.svg"))), "is not plain data"), + (format!("app.activeDocument.saveAs({{'\\u0000folderRef': {}}});", quoted(&dir)), "is not plain data"), + (format!("app.activeDocument.saveAs({f}, {{typename: 'Nope'}});"), "saveAs options must be"), + (format!("app.activeDocument.saveAs({f}, new ExportOptionsSVG());"), "saveAs options must be"), + (format!("var o = new IllustratorSaveOptions(); o.compressed = 'yes'; app.activeDocument.saveAs({f}, o);"), "must be true or false"), + ( + format!("var o = new IllustratorSaveOptions(); o.compatibility = Compatibility.ILLUSTRATOR8; app.activeDocument.saveAs({f}, o);"), + "is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.trimMarks = true; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.trimMarks is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.colorCompression = 'Unrelated.None'; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.colorCompression is not available yet", + ), + (format!("var o = new PDFSaveOptions(); o.pDFPreset = '{huge}'; app.activeDocument.saveAs({f}, o);"), "too long"), + (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), + (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), + (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 1e9; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at most", + ), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 0.5; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at least 1", + ), + ( + format!("var p = new ExportOptionsPNG24(); p.horizontalScale = 50; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "not available yet", + ), + ( + format!("var p = new ExportOptionsJPEG(); p.qualitySetting = 101; app.activeDocument.exportFile({f}, ExportType.JPEG, p);"), + "from 0 to 100", + ), + (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), + (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), + (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), + (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + (format!("var o = new PDFSaveOptions(); o.trimMark = true; app.activeDocument.saveAs({f}, o);"), "PDFSaveOptions has no option trimMark"), + ( + format!("var p = new ExportOptionsPNG24(); p.transparancy = false; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "ExportOptionsPNG24 has no option transparancy", + ), + (format!("app.open({f}, undefined, {{pageToOpne: 2}});"), "PDFFileOptions has no option pageToOpne"), + ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), + (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), + ]; + for (case, wanted) in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(wanted), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("missing.svg")))); + assert!(e.contains(crate::script::files::NOT_FOUND), "{e}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a +/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its +/// own path, so nothing is written or opened at the path the script put there. +#[test] +fn a_forged_file_is_refused() { + let base = folder("forged"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("real.svg"), "").unwrap(); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let (x, real) = (quoted(&dir.join("x.svg")), quoted(&dir.join("real.svg"))); + let (out, secret) = (quoted(&base.join("outside/x.svg")), quoted(&base.join("outside/secret.svg"))); + let calls = |f: &str, read: &str| { + [format!("app.activeDocument.saveAs({f});"), format!("app.activeDocument.exportFile({f}, ExportType.SVG);"), format!("app.open({read});")] + }; + for made in ["Object.create(File.prototype)", "{}"] { + let make = |p: &str| format!("(function () {{ var f = {made}; f.__vcPath = {p}; return f; }})()"); + for case in calls(&make(&x), &make(&real)) { + let text = format!("Folder.userData; try {{ {case} vc.log('ran'); }} catch (e) {{ vc.log([e.name, e.message]); }}"); + let log = logged(&mut s, &base, &text); + assert_eq!(log[0][0], json!("TypeError"), "{case}: {log}"); + assert!(log[0][1].as_str().unwrap().contains("needs a File"), "{case}: {log}"); + } + } + let moved = |from: &str, to: &str| format!("(function () {{ var f = new File({from}); f.__vcPath = {to}; return f; }})()"); + for case in calls(&moved(&out, &x), &moved(&secret, &real)) { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + assert!(!dir.join("x.svg").exists() && !dir.join("x.svg.svg").exists(), "nothing is written at the forged path"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1); + assert_eq!(s.documents().len(), 1, "nothing is opened"); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// A document from an earlier run is stale, and saving it throws. +#[test] +fn a_stale_document_is_not_saved() { + let base = folder("stale"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + run(&mut s, &base, "#targetengine keep\nvar held = app.activeDocument;").unwrap(); + let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg")))); + assert!(e.contains("Stale document"), "{e}"); + assert!(!dir.join("x.svg").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// `open` applies the page and crop box of its options to a PDF. +#[test] +fn open_takes_the_page_and_crop_box_of_its_options() { + let base = folder("pdf"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let pdf = dir.join("two.pdf"); + s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX, typename: 'PDFFileOptions', later: undefined}});\n\ + vc.log(g.documentColorSpace);", + quoted(&pdf) + ), + ); + assert_eq!(out, json!(["DocumentColorSpace.CMYK"])); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf))); + assert!(!e.is_empty(), "a page the file does not have"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page"); + // Options left undefined are left out: the file opens as it does without options. + let undefined = format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: undefined, pDFCropToBox: undefined}});", quoted(&pdf)); + logged(&mut s, &base, &undefined); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn crop_only_options_apply_to_an_editable_pdf() { + let base = folder("pdfcroponly"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("editable.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": pdf.to_string_lossy(), "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::editing(&std::fs::read(&pdf).unwrap()).is_some_and(|e| e.intact)); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&pdf))); + let original = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf))); + let cropped = s.active().unwrap().doc.artboards[0].rect; + assert!(cropped.width() > original.width() && cropped.height() > original.height()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() { + let base = folder("explicitcropbox"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["ai", "pdf"] { + let file = dir.join(format!("editable.{extension}")); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": file.to_string_lossy(), "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&file).unwrap(), None)); + let path = quoted(&file); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + let default = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFTRIMBOX}});")); + let trim = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFCROPBOX}});")); + let crop = s.active().unwrap().doc.artboards[0].rect; + // Without the embedded document and without a crop box, the file opens at its trim box too. + s.execute("document.open", &json!({"path": file.to_string_lossy(), "editingData": false})).unwrap(); + let implicit = s.active().unwrap().doc.artboards[0].rect; + assert_eq!((implicit.width(), implicit.height()), (trim.width(), trim.height()), "{extension}"); + assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}"); + assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_rejects_files_over_the_read_limit() { + let base = folder("openreadlimit"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = dir.join("large.svg"); + std::fs::write(&file, b"").unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + let count = s.documents().len(); + std::fs::OpenOptions::new().write(true).open(&file).unwrap().set_len(crate::cmd::fileio::SCRIPT_OPEN_MAX_BYTES as u64 + 1).unwrap(); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}"); + assert_eq!(s.documents().len(), count); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn pdf_open_options_reject_other_detected_formats() { + let base = folder("pdfoptionsformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let native = dir.join("native.pdf"); + s.execute("file.saveAs", &json!({"path": native.to_string_lossy(), "format": "vectorcraft"})).unwrap(); + let svg = dir.join("drawing.pdf"); + std::fs::write(&svg, b"").unwrap(); + let count = s.documents().len(); + let uid = s.active().unwrap().uid; + for file in [&native, &svg] { + for options in ["{pageToOpen: 2}", "{pDFCropToBox: PDFBoxType.PDFMEDIABOX}"] { + let script = format!("Folder.userData; app.open(new File({}), undefined, {options});", quoted(file)); + let e = failure(&mut s, &base, &script); + assert!(e.contains("PDF open options require a PDF file"), "{e}"); + assert_eq!(s.documents().len(), count); + assert_eq!(s.active().unwrap().uid, uid); + } + } + let pdf = dir.join("actual.svg"); + s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf))); + assert_eq!(s.documents().len(), count + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_treats_null_pdf_options_as_omitted() { + let base = folder("nullpdfdefaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({})).unwrap(); + for extension in ["svg", "vectorcraft"] { + let file = dir.join(format!("drawing.{extension}")); + s.execute("file.saveAs", &json!({"path": file.to_string_lossy()})).unwrap(); + for options in ["page: null", "cropTo: null", "page: null, cropTo: null"] { + let count = s.documents().len(); + logged(&mut s, &base, &format!("Folder.userData; vc.run('document.open', {{path: {}, {options}}});", quoted(&file))); + assert_eq!(s.documents().len(), count + 1, "{extension}: {options}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn explicit_null_options_do_not_save_export_open_or_close() { + let base = folder("nulloptions"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let file = dir.join("existing.svg"); + let original = b""; + std::fs::write(&file, original).unwrap(); + let f = format!("new File({})", quoted(&file)); + for call in [ + format!("app.activeDocument.saveAs({f}, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.GIF, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.PNG8, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.TIFF, null);"), + format!("app.open({f}, null);"), + format!("app.open({f}, undefined, null);"), + "app.activeDocument.close(null);".into(), + ] { + let e = failure(&mut s, &base, &format!("Folder.userData; {call}")); + assert!(e.contains("TypeError"), "{call}: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), original, "{call}"); + assert_eq!(s.documents().len(), 1, "{call}"); + assert!(!s.active().unwrap().is_dirty(), "{call}"); + } + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs({f}, undefined);")); + assert_ne!(std::fs::read(&file).unwrap(), original); + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its +/// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it. +#[test] +fn full_name_path_saved_and_close_follow_the_documents_file() { + let base = folder("fullname"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.fullName instanceof File, d.fullName.name === d.name, d.fullName.fsName === new File(d.name).fsName, d.path === '', d.saved]);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); vc.log(d.saved);\n\ + d.saveAs(new File(dir + '/a.svg'));\n\ + vc.log([d.fullName instanceof File, d.fullName.fsName, d.fullName.name, d.path instanceof Folder, d.path.fsName, d.saved]);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); vc.log(d.saved);\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + var before = new File(dir + '/a.svg').length; d.close(SaveOptions.SAVECHANGES);\n\ + vc.log([app.documents.length, new File(dir + '/a.svg').length > before]);\n\ + var n = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.run('shape.rectangle', {{x: 10, y: 10, width: 5, height: 5}});\n\ + e = ''; try {{ n.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + n.close(SaveOptions.DONOTSAVECHANGES); vc.log(app.documents.length);" + ), + ); + assert_eq!(out[0], json!([true, true, true, true, true]), "an untouched document that has no file"); + assert_eq!(out[1], json!(false), "an edit leaves changes to save"); + let file = dir.join("a.svg"); + assert_eq!( + out[2], + json!([true, file.to_string_lossy(), "a.svg", true, dir.to_string_lossy(), true]), + "after saveAs the document's file and folder" + ); + assert_eq!(out[3], json!(false)); + assert!(out[4][0].as_str().unwrap().contains("unsaved changes"), "{}", out[4]); + assert_eq!(out[4][1], json!(1), "without SaveOptions the document stays open"); + assert_eq!(out[5], json!([0, true]), "SAVECHANGES saves the edit to the document's file and closes it"); + assert!(out[6][0].as_str().unwrap().contains("no file to save"), "{}", out[6]); + assert_eq!(out[6][1], json!(1), "SAVECHANGES without a file leaves the document open"); + assert_eq!(out[7], json!(0)); + assert!(s.documents().is_empty()); + let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');"); + assert!(e.contains("SaveOptions"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. +#[test] +fn a_document_without_unsaved_changes_closes_with_any_save_options() { + let base = folder("closeclean"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File(dir + '/a.svg'));\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.saved, e.saved, app.documents.length]);\n\ + d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);\n\ + e.close(); vc.log(app.documents.length);" + ), + ); + assert_eq!(out, json!([[true, true, 2], 1, 0])); + let _ = std::fs::remove_dir_all(base); +} + +/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the +/// one its file's extension names. +#[test] +fn closing_with_save_changes_keeps_the_documents_format() { + let base = folder("closeformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);" + ), + ); + let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); + assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + let pdf = vectorcraft_pdf::import(&bytes).unwrap(); + let mut sizes = vec![]; + for l in &pdf.layers { + l.walk(&mut |n| sizes.extend(n.geometric_bounds().map(|b| (b.width(), b.height())))); + } + let near = |(w, h): (f64, f64), (x, y): (f64, f64)| (w - x).abs() < 0.01 && (h - y).abs() < 0.01; + assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}"); + assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards +/// throws before writing and leaves the document open, so no change is left out of its file. +#[test] +fn closing_with_save_changes_refuses_a_save_of_some_artboards() { + let base = folder("closerange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = '2'; d.saveAs(new File({d} + '/r.pdf'), o);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}});\n\ + var e = ''; try {{ d.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert!(out[0][0].as_str().unwrap().contains("some of its artboards"), "{}", out[0]); + assert_eq!(out[0][1], json!(1), "the document stays open"); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("r.pdf")).unwrap()).unwrap(); + let mut drawn = 0; + for l in &pdf.layers { + l.walk(&mut |n| drawn += usize::from(n.geometric_bounds().is_some_and(|b| (b.width() - 5.0).abs() < 0.01))); + } + assert_eq!(drawn, 0, "the file is left as the first save wrote it"); + assert!(s.active().unwrap().is_dirty(), "the change is still unsaved"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { + let base = folder("closefullrange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range, boards) in [("one", "1", 1), ("two", "1-2", 2)] { + let file = dir.join(format!("{name}.pdf")); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": boards})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.activeDocument, o = new PDFSaveOptions(); o.artboardRange = '{range}';\n\ + d.saveAs(new File({}), o);", + quoted(&file), + ), + ); + let before = std::fs::read(&file).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty()); + assert_ne!(std::fs::read(&file).unwrap(), before); + } + s.execute("file.new", &json!({})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PDFSaveOptions(); o.artboardRange = '1'; app.activeDocument.saveAs(new File({}), o);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});", + quoted(&dir.join("grown.pdf")), + ), + ); + let before = std::fs::read(dir.join("grown.pdf")).unwrap(); + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF +/// last saved without its artboards (`useArtboards: false`) is refused, and a `.ai` file whose +/// `range` names only the separate artboard files keeps every artboard and is saved. +#[test] +fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { + let base = folder("closeencoder"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("art.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("document.save", &json!({"path": pdf.to_string_lossy(), "useArtboards": false})).unwrap(); + let before = std::fs::read(&pdf).unwrap(); + let e = failure( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(std::fs::read(&pdf).unwrap(), before, "the PDF is left as it was"); + let mut s = session(&base); + data_folder(&mut s, &base); + let ai = dir.join("all.ai"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": ai.to_string_lossy(), "separateArtboards": true, "range": "2"})).unwrap(); + let before = std::fs::read(&ai).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes"); + assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native +/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves +/// them; a `range` the save refuses still refuses. +#[test] +fn closing_with_save_changes_saves_files_that_keep_every_artboard() { + let base = folder("closekeepall"); + let dir = { + let mut s = session(&base); + data_folder(&mut s, &base) + }; + for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] { + let mut s = session(&base); + data_folder(&mut s, &base); + let file = dir.join(name); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let mut save = options.clone(); + save["path"] = json!(file.to_string_lossy()); + s.execute("document.save", &save).unwrap(); + let before = std::fs::read(&file).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{name}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{name}"); + s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() { + let base = folder("closeepsboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range) in [("single", "2"), ("several", "1-2")] { + let file = dir.join(format!("{name}.eps")); + let path = quoted(&file); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50);\n\ + vc.run('artboard.new', {{x: 150, y: 0, width: 100, height: 50}});\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 100, height: 50}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 20, height: 20}});\n\ + var o = new EPSSaveOptions(); o.saveMultipleArtboards = true; o.artboardRange = '{range}';\n\ + d.saveAs(new File({path}), o);" + ), + ); + let before = std::fs::read(&file).unwrap(); + let nodes = s.active().unwrap().doc.node_count(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 40, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{range}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{range}"); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 3, "{range}"); + assert!(s.active().unwrap().doc.node_count() > nodes, "{range}"); + logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { + let base = folder("closesvgboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["svg", "svgz"] { + for preserve in [false, true] { + let file = dir.join(format!("drawing-{preserve}.{extension}")); + let path = quoted(&file); + let save = if preserve { + format!("vc.run('file.saveAs', {{path: {path}, preserveEditing: true}});") + } else { + format!("d.saveAs(new File({path}));") + }; + logged(&mut s, &base, &format!("Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50); {save}")); + let before = std::fs::read(&file).unwrap(); + logged(&mut s, &base, "Folder.userData; vc.run('artboard.new', {x: 300, y: 0, width: 60, height: 80});"); + let uid = s.active().unwrap().uid; + if preserve { + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(s.documents().is_empty()); + assert_ne!(std::fs::read(&file).unwrap(), before); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + } else { + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{extension}: {e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().uid, uid); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + assert!(s.active().unwrap().is_dirty()); + assert_eq!(std::fs::read(&file).unwrap(), before); + } + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn document_path_reflection_describes_folders_and_unsaved_strings() { + let base = folder("pathreflection"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add();\n\ + vc.log([d.reflect.find('path').dataType, d.path === '']);\n\ + d.saveAs(new File({})); vc.log([d.reflect.find('path').dataType, d.path instanceof Folder ? 'Folder' : typeof d.path]);\n\ + vc.log([d.path instanceof Folder, d.path.fsName]);", + quoted(&dir.join("saved.svg")), + ), + ); + assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]])); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `Document.saved` records the document's saved state without saving it: `true` lets +/// `close()` close a document with edits, and `false` makes an untouched one ask. +#[test] +fn setting_saved_records_the_saved_state() { + let base = folder("setsaved"); + let mut s = session(&base); + data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20});\n\ + vc.log(d.saved); d.saved = true; vc.log(d.saved); d.close(); vc.log(app.documents.length);\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.log(e.saved); e.saved = false; vc.log(e.saved);\n\ + var m = ''; try { e.close(); } catch (x) { m = String(x); } vc.log([m, app.documents.length]);\n\ + m = ''; try { e.saved = 'yes'; } catch (x) { m = String(x); } vc.log(m);", + ); + assert_eq!(out[0], json!(false), "an edit leaves changes to save"); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(0), "close() closes a document set as saved"); + assert_eq!(out[3], json!(true)); + assert_eq!(out[4], json!(false)); + assert!(out[5][0].as_str().unwrap().contains("unsaved changes"), "{}", out[5]); + assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open"); + assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]); + assert!(s.active().unwrap().is_dirty(), "the state stays after the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings of a save go to the console after the method's name. +#[test] +fn save_as_writes_its_warnings_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap(); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A point change that waits to be written counts as an unsaved change for `saved` and `close`. +#[test] +fn waiting_point_changes_count_as_unsaved_changes() { + let base = folder("pendingpoints"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/a.svg'));\n\ + d.pathItems[0].pathPoints[0].anchor = [1, 2]; vc.log(d.saved);\n\ + d.saved = true; d.pathItems[0].pathPoints[0].anchor = [3, 4];\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert_eq!(out[0], json!(false), "a waiting point change is unsaved"); + assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]); + assert_eq!(out[1][1], json!(1), "close() keeps the document open"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unchanged_saved_assignments_do_not_record_commands() { + let base = folder("savednoop"); + let mut s = session(&base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + d.saved = d.saved; d.saved = true; vc.log(d.saved);\n\ + d.saved = false; d.saved = d.saved; d.saved = false; vc.log(d.saved);\n\ + d.saved = true; d.saved = d.saved; vc.log(d.saved);", + ); + assert_eq!(out, json!([true, false, true])); + let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect(); + assert_eq!(changes, [json!(false), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + +/// With automation read roots that leave out the document's file, `fullName` and `path` throw +/// instead of naming another file. +#[test] +fn full_name_and_path_leave_out_a_file_outside_the_read_roots() { + let base = folder("fullnameroots"); + let mut s = session(&base); + data_folder(&mut s, &base); + let file = base.join("outside/hidden.svg"); + s.execute("file.new", &json!({})).unwrap(); + s.execute("document.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let query = "var d = app.activeDocument; vc.log([d.fullName.name, d.fullName.fsName, d.path === '' ? '' : d.path.fsName]);"; + let out = logged(&mut s, &base, query); + let outside = base.join("outside"); + assert_eq!(out[0], json!(["hidden.svg", file.to_string_lossy(), outside.to_string_lossy()]), "no read roots: the whole path"); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("main"), &base.join("settings")], &[&base.join("settings")]).unwrap().unwrap(); + let hidden = "var d = app.activeDocument, r = [];\n\ + try { r.push(d.fullName.fsName); } catch (e) { r.push(e.message); }\n\ + try { r.push(String(d.path)); } catch (e) { r.push(e.message); }\n\ + vc.log(r);"; + let out = crate::file_access::confine(Some(&roots), || logged(&mut s, &base, hidden)); + for m in out[0].as_array().unwrap() { + let m = m.as_str().unwrap(); + assert!(m.starts_with(DENIED) && m.ends_with("hidden.svg"), "{m}"); + assert!(!m.contains("outside"), "the folder outside the read roots is not named: {m}"); + } + let before = std::fs::read(&file).unwrap(); + let e = failure( + &mut s, + &base, + "vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was"); + assert_eq!(s.documents().len(), 1, "the document stays open"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn implicit_multifile_save_redacts_preflight_refusals_before_writing() { + let base = folder("savepreflight"); + let mut s = session(&base); + let hidden = base.join("private-save-directory"); + std::fs::create_dir_all(&hidden).unwrap(); + let path = hidden.join("drawing.vectorcraft"); + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + let saved = s.execute("document.save", &json!({"path": path.to_string_lossy(), "separateArtboards": true})).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| PathBuf::from(p.as_str().unwrap())).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(|p| std::fs::read(p).unwrap()).collect(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let main = base.join("main"); + let roots = crate::file_access::AutomationRoots::new(&[&main], &[&main]).unwrap().unwrap(); + let e = crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("automation path rejected"), "{e}"); + assert!(!e.contains("private-save-directory"), "{e}"); + assert!(!e.contains(path.to_string_lossy().as_ref()), "{e}"); + assert!(s.active().unwrap().is_dirty()); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes); + } + let explicit = + crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string(); + assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name +/// that is not a preset either way is refused. +#[test] +fn a_bracketed_pdf_preset_names_the_built_in_preset() { + let base = folder("brackets"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.pDFPreset = '[Smallest File Size]'; d.saveAs(new File(dir + '/small.pdf'), o);\n\ + o.pDFPreset = '[Illustrator Default]'; d.saveAs(new File(dir + '/default.pdf'), o);\n\ + o.pDFPreset = '[PDF/X-4:2008]'; d.saveAs(new File(dir + '/x4.pdf'), o);" + ), + ); + let small = std::fs::read(dir.join("small.pdf")).unwrap(); + assert!(String::from_utf8_lossy(&small[..200.min(small.len())]).contains("/Linearized 1"), "Smallest File Size writes a linearized file"); + assert!(dir.join("default.pdf").is_file()); + let x4 = String::from_utf8_lossy(&std::fs::read(dir.join("x4.pdf")).unwrap()).into_owned(); + assert!(x4.contains("PDF/X-4"), "the PDF/X-4 preset writes a PDF/X-4 file"); + for bad in ["[Nope]", "[Basic Default]", "[Ilustrator Default]"] { + let e = failure( + &mut s, + &base, + &format!("Folder.userData; var o = new PDFSaveOptions(); o.pDFPreset = '{bad}'; app.activeDocument.saveAs(new File({d} + '/n.pdf'), o);"), + ); + assert!(e.contains("unknown PDF preset"), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A number given as `artboardRange` is read as `String(number)` reads it. +#[test] +fn a_number_artboard_range_names_that_artboard() { + let base = folder("rangenumber"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = 2; d.saveAs(new File(dir + '/two.pdf'), o);" + ), + ); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("two.pdf")).unwrap()).unwrap(); + assert_eq!(pdf.artboards.len(), 1, "one page"); + let r = pdf.artboards[0].rect; + assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of +/// `artboardRange`; without it the range is not used, and only a value that is not written as a +/// range throws. +#[test] +fn save_multiple_artboards_writes_a_file_per_artboard() { + let base = folder("multiple"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let names = |sub: &str| { + let mut v: Vec = std::fs::read_dir(dir.join(sub)).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + }; + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var names = ['ai', 'eps', 'aione', 'epsone', 'aioff'];\n\ + for (var i = 0; i < names.length; i++) new Folder(dir + '/' + names[i]).create();\n\ + var a = new IllustratorSaveOptions(); a.saveMultipleArtboards = true; d.saveAs(new File(dir + '/ai/a.ai'), a);\n\ + var e = new EPSSaveOptions(); e.saveMultipleArtboards = true; d.saveAs(new File(dir + '/eps/a.eps'), e);\n\ + a.artboardRange = '2'; d.saveAs(new File(dir + '/aione/a.ai'), a);\n\ + e.artboardRange = 2; d.saveAs(new File(dir + '/epsone/a.eps'), e);\n\ + a.saveMultipleArtboards = false; d.saveAs(new File(dir + '/aioff/a.ai'), a);" + ), + ); + assert_eq!(names("ai"), ["a-Artboard-1.ai", "a-Artboard-2.ai", "a.ai"], "the file and one for each of the two artboards"); + assert_eq!(names("eps"), ["a.eps", "a_Artboard-1.eps", "a_Artboard-2.eps"], "the central file and one for each of the two artboards"); + assert_eq!(names("aione"), ["a-Artboard-2.ai", "a.ai"], "the file and one for artboard 2"); + assert_eq!(names("epsone"), ["a.eps"], "one artboard: its file alone"); + let eps = String::from_utf8_lossy(&std::fs::read(dir.join("epsone/a.eps")).unwrap()).into_owned(); + let bbox = eps.lines().find(|l| l.starts_with("%%BoundingBox:")).unwrap_or_default(); + assert_eq!(bbox.split_whitespace().skip(1).collect::>(), ["0", "0", "60", "80"], "the file holds artboard 2: {bbox}"); + assert_eq!(names("aioff"), ["a.ai"], "without saveMultipleArtboards the range is not used"); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = 3; \ + app.activeDocument.saveAs(new File({d} + '/aioff/c.ai'), a);" + ), + ); + assert!(dir.join("aioff/c.ai").is_file(), "a range past the document's artboards is not used and does not stop the save"); + for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "','", "' , '", "-1", "2.5", "0"] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = {bad}; \ + app.activeDocument.saveAs(new File({d} + '/aioff/b.ai'), a);" + ), + ); + assert!(e.contains("range"), "{bad}: {e}"); + } + assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 0a71638c92..2794e929b2 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -260,7 +260,10 @@ fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { assert_eq!(out, vec![json!([false, 14.4])]); assert_eq!(undo_steps(&s), before + 1); match &s.active().unwrap().doc.node(id).unwrap().kind { - NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + NodeKind::Text(t) => { + assert_eq!(t.plain_text(), "abc"); + assert!(!t.runs.is_empty() && t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs); + } _ => panic!("not text"), } // A fixed leading set to its own value is still no change. @@ -371,7 +374,10 @@ fn turning_auto_leading_off_keeps_each_characters_leading() { assert!(e.contains("autoLeading cannot be turned off"), "{e}"); assert_eq!(undo_steps(&s), before); match &s.active().unwrap().doc.node(id).unwrap().kind { - NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + NodeKind::Text(t) => { + assert_eq!(t.plain_text(), "ab\ncd"); + assert!(!t.runs.is_empty() && t.runs.iter().all(|r| r.style.leading.is_none()), "{:?}", t.runs); + } _ => panic!("not text"), } } diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 3a4f8952f4..687df5cd0e 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -729,7 +729,8 @@ fn a_temporary_file_starts_private() { } /// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named -/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) +/// users the sidecar's group bits would let in. The default ACL is set through its extended +/// attribute, so the test runs where the `acl` tools are not installed. #[cfg(target_os = "linux")] #[test] fn a_replaced_sidecar_takes_no_inherited_acl() { @@ -741,11 +742,22 @@ fn a_replaced_sidecar_takes_no_inherited_acl() { &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), ); let path = PathBuf::from(log[0].as_str().unwrap()); - let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status(); - if !set.is_ok_and(|s| s.success()) { - let _ = std::fs::remove_dir_all(base); - return; + let parent = path.parent().unwrap(); + // `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--` as the kernel's attribute: version 2, then tag, + // permissions and id per entry. + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 6u16, u32::MAX), (0x02, 6, 65534), (0x04, 4, u32::MAX), (0x10, 6, u32::MAX), (0x20, 4, u32::MAX)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); } + rustix::fs::setxattr(parent, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) + .unwrap_or_else(|e| panic!("setting the default ACL (the temporary folder's file system needs ACLs): {e}")); + let mut buf = vec![0u8; 4096]; + let probe = parent.join("probe"); + std::fs::write(&probe, b"").unwrap(); + assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL"); + std::fs::remove_file(&probe).unwrap(); logged( &mut s, &base, @@ -753,9 +765,11 @@ fn a_replaced_sidecar_takes_no_inherited_acl() { var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", ); assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); - let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap(); - let acl = String::from_utf8_lossy(&acl.stdout); - assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}"); + assert_eq!( + rustix::fs::getxattr(&path, "system.posix_acl_access", &mut buf[..]), + Err(rustix::io::Errno::NODATA), + "the replacement takes no ACL entry the sidecar lacked" + ); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index 055711cb43..07feda9d7c 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -235,7 +235,7 @@ fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() { run(&mut s, "select.set", json!({"ids": [a.0]})); let v = ViewInfo::default(); s.select_tool("selection", v).unwrap(); - assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move); + assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::SelectionMove); assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow); assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow); } diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index 21967473bb..380126535f 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -79,6 +79,7 @@ fn file_names(dir: &std::path::Path) -> Vec { /// Windows does not allow replacing a read-only file or writing into it, so the write fails. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { let root = fresh_dir("rename-case-fails"); @@ -157,6 +158,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { assert!(holds(&[][..], &[])); } +#[cfg(unix)] +#[test] +fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() { + use crate::store::{NOT_PLAIN, read_capped_plain}; + let root = fresh_dir("plain-read"); + let target = root.join("target.bin"); + std::fs::write(&target, b"outside").unwrap(); + let link = root.join("profile.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string())); + let folder = root.join("folder"); + std::fs::create_dir(&folder).unwrap(); + assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string())); + assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec())); + assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec())); + assert!(read_capped_plain(&target, 6).is_err()); +} + #[test] fn a_saved_preset_replaces_an_oversized_file_in_its_place() { let root = fresh_dir("oversized-put"); diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index af3eb52936..b9bd87c492 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -34,12 +34,10 @@ fn arrow_align_is_set_per_stroke_and_validated() { #[test] fn profiles_come_from_the_preset_catalogue() { let (mut s, id) = session_with_line(); - for p in WidthProfile::PRESETS { - s.execute("stroke.set", &json!({"profile": p.id})).unwrap(); - let st = stroke(&s, id); - assert_eq!(WidthProfile::id_of(st.profile.as_ref()), p.id); - } - assert!(stroke(&s, id).profile.is_some()); + s.execute("stroke.set", &json!({"profile": "lens"})).unwrap(); + assert_eq!(stroke(&s, id).profile.map(|p| p.points), Some(vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)])); + s.execute("stroke.set", &json!({"profile": "pinch"})).unwrap(); + assert_eq!(stroke(&s, id).profile.map(|p| p.points), Some(vec![(0.0, 1.0, 1.0), (0.5, 0.25, 0.25), (1.0, 1.0, 1.0)])); s.execute("stroke.set", &json!({"profile": "uniform"})).unwrap(); assert!(stroke(&s, id).profile.is_none(), "uniform is the plain stroke"); assert!(s.execute("stroke.set", &json!({"profile": "zigzag"})).is_err()); @@ -53,9 +51,12 @@ fn profiles_come_from_the_preset_catalogue() { for a in vectorcraft_doc::Arrowhead::ALL { let name = serde_json::to_value(&a).unwrap(); assert!(spec.params.contains(name.as_str().unwrap()), "{name}"); - s.execute("stroke.set", &json!({"endArrow": name})).unwrap(); - assert_eq!(stroke(&s, id).end_arrow, Some(a)); } + s.execute("stroke.set", &json!({"endArrow": "TriangleOpen", "startArrow": "Diamond"})).unwrap(); + let st = stroke(&s, id); + assert_eq!((st.start_arrow, st.end_arrow), (Some(Arrowhead::Diamond), Some(Arrowhead::TriangleOpen))); + assert!(s.execute("stroke.set", &json!({"endArrow": "Arrow999"})).is_err()); + assert_eq!(stroke(&s, id).end_arrow, Some(Arrowhead::TriangleOpen), "a refused name changes nothing"); } #[test] diff --git a/crates/engine/src/tests/stylepanel.rs b/crates/engine/src/tests/stylepanel.rs index d414dcbb64..0c2cbeac62 100644 --- a/crates/engine/src/tests/stylepanel.rs +++ b/crates/engine/src/tests/stylepanel.rs @@ -125,9 +125,12 @@ fn override_character_color_clears_the_run_fill() { assert_eq!(run(&mut s, "graphicStyle.setOptions", json!({}))["overrideCharColor"], true); let a = text(&mut s, 100.0); run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [a.0]})); - assert!(runs(&s, a).iter().all(|(f, _)| *f != Paint::None)); + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + let painted = runs(&s, a); + assert!(!painted.is_empty() && painted.iter().all(|(f, _)| *f == red), "{painted:?}"); run(&mut s, "graphicStyle.apply", json!({"name": "Blue", "ids": [a.0]})); - assert!(runs(&s, a).iter().all(|(f, st)| *f == Paint::None && *st == Paint::None)); + let styled = runs(&s, a); + assert!(styled.len() == painted.len() && styled.iter().all(|(f, st)| *f == Paint::None && *st == Paint::None), "{styled:?}"); assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.fill_paint(), Paint::solid(Color::from_hex("#0000ff").unwrap())); // Off: they keep it (the style's paint draws over them). assert_eq!(run(&mut s, "graphicStyle.setOptions", json!({"overrideCharColor": false}))["overrideCharColor"], false); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index ff02889253..b3d4d075e9 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -722,7 +722,8 @@ fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() { json!({"ids": [a.0], "gradient": {"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]}}), ); let Paint::Gradient(g) = fill(&s, a) else { panic!("a gradient") }; - assert!(g.gradient.stops.iter().all(|st| matches!(st.color, Color::Cmyk { .. }))); + assert_eq!(g.gradient.stops.len(), 2, "{:?}", g.gradient.stops); + assert!(g.gradient.stops.iter().all(|st| matches!(st.color, Color::Cmyk { .. })), "{:?}", g.gradient.stops); // A swatch made from a hex colour is CMYK as well; the document round-trips natively. let name = run(&mut s, "swatch.new", json!({"color": "#00ff00"}))["name"].as_str().unwrap().to_string(); assert_eq!(doc(&s).swatch(&name).and_then(|w| w.paint.color()), Some(managed(Color::rgb(0.0, 1.0, 0.0)))); diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 19d2333b6e..5b239f27d8 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -265,6 +265,7 @@ fn nature_icons_library_places_and_survives_save() { for (i, name) in names.iter().enumerate() { let symbol = &library["symbols"][i]; let size = symbol["size"].as_array().unwrap(); + assert_eq!(size.len(), 2, "{name}: width and height"); assert!(size.iter().all(|n| n.as_f64().is_some_and(|n| n.is_finite() && n > 0.0)), "{name}"); let added = run( &mut s, diff --git a/crates/engine/src/tests/textcombos.rs b/crates/engine/src/tests/textcombos.rs index c0f3ad5ff4..d7a98851e2 100644 --- a/crates/engine/src/tests/textcombos.rs +++ b/crates/engine/src/tests/textcombos.rs @@ -161,7 +161,11 @@ fn auto_height_x_composer() { } s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap(); s.execute("text.setStyle", &json!({"id": id.0, "justify": "justifyAll"})).unwrap(); - assert!(text(&s, id).paragraph_styles().iter().all(|p| p.composer == Composer::SingleLine && p.justify == Justify::JustifyAll)); + let t = text(&s, id); + assert_eq!(t.paragraph_count(), 2); + for k in 0..2 { + assert_eq!((t.para_at(k).composer, t.para_at(k).justify), (Composer::SingleLine, Justify::JustifyAll), "paragraph {k}"); + } assert_tight(&s, id, "justified"); } diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 96403dcaa0..25324caff6 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -323,7 +323,8 @@ fn optical_set_format_clears_existing_pair_override() { let result = s.execute("text.setFormat", &json!({"ids": [id.0], "kerning": "optical"})).unwrap(); assert_eq!(result["kerning"], "optical"); let t = obj(&s, id); - assert!(t.runs.iter().all(|r| r.style.optical_kerning)); + assert_eq!(t.plain_text(), "III"); + assert!(!t.runs.is_empty() && t.runs.iter().all(|r| r.style.optical_kerning), "{:?}", t.runs); assert!(t.runs.iter().all(|r| r.style.kerning.is_none()), "choosing Optical clears the manual value"); } @@ -488,8 +489,10 @@ fn char_style_range_past_u32_styles_nothing() { let mut s = session(); let id = text(&mut s, "Hello world"); s.execute("charStyle.new", &json!({"name": "Big", "attrs": {"size": 40.0}})).unwrap(); + let before = obj(&s, id); + assert!(!before.runs.is_empty() && before.runs.iter().all(|r| r.style.size == 20.0 && r.style.style_name.is_none()), "{:?}", before.runs); s.execute("charStyle.apply", &json!({"name": "Big", "id": id.0, "start": 1u64 << 32, "end": (1u64 << 32) + 5})).unwrap(); - assert!(obj(&s, id).runs.iter().all(|r| r.style.size == 20.0 && r.style.style_name.is_none()), "{:?}", obj(&s, id).runs); + assert_eq!(obj(&s, id), before, "no character is styled"); } #[test] @@ -2008,7 +2011,8 @@ fn the_eyedropper_styles_the_whole_story_that_select_all_selected() { let r = s.execute("appearance.copyFrom", &json!({"source": source})).unwrap(); assert_eq!(r, json!({"ids": [a.0, b.0]})); for id in [a, b] { - assert!(obj(&s, id).runs.iter().all(|r| (r.style.size - 30.0).abs() < 1e-9), "every character of frame {} takes the size", id.0); + let runs = obj(&s, id).runs; + assert!(!runs.is_empty() && runs.iter().all(|r| (r.style.size - 30.0).abs() < 1e-9), "every character of frame {} takes the size", id.0); } } @@ -2223,7 +2227,8 @@ fn a_type_step_keeps_a_story_that_left_the_edited_frame_selected() { let c = selected_story_moved_into_a_new_frame(&mut s, a, b); // Alt+Right steps the tracking of the selected text, not the kerning at a caret. key(&mut s, ToolKey::Right, Mods { alt: true, ..Mods::default() }); - assert!(obj(&s, c).runs.iter().all(|r| r.style.tracking > 0.0), "every character of the story takes the step"); + let runs = obj(&s, c).runs; + assert!(!runs.is_empty() && runs.iter().all(|r| r.style.tracking > 0.0), "every character of the story takes the step: {runs:?}"); // A key that does nothing leaves it selected as well. key(&mut s, ToolKey::BracketLeft, Mods::default()); assert!(third_frame_highlighted(&mut s)); @@ -2567,6 +2572,7 @@ fn convert_to_text_in_one_frame_leaves_the_other_frames() { let (ta, tb) = (obj(&s, a), obj(&s, b)); assert_eq!(ta.plain_text(), in_a, "the first frame's text is as it was"); assert!(ta.para_at(0).list.is_some(), "the first frame stays a list"); + assert!(tb.paragraph_count() > 1, "{:?}", tb.plain_text()); assert!((0..tb.paragraph_count()).all(|k| tb.para_at(k).list.is_none()), "the edited frame leaves its list"); assert!(tb.plain_text().contains("\u{2022}\t"), "the edited frame holds its bullets as characters"); } @@ -3765,7 +3771,7 @@ fn the_glyph_query_shapes_an_overflowing_character_in_its_paragraph_direction() let boxed = create(&mut s, text, rtl, char_ltr, 30.0); let lay = vectorcraft_text::layout(db, &obj(&s, boxed)); - assert!(lay.glyphs.iter().all(|g| g.byte < 2), "{text:?}: the second paragraph overflows"); + assert!(!lay.glyphs.is_empty() && lay.glyphs.iter().all(|g| g.byte < 2), "{text:?}: only the first paragraph is laid out"); let r = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": at})).unwrap(); assert_eq!(r["chosen"], json!(face.glyph_for(drawn)), "{text:?}: the glyph drawn when it fits"); } diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 7a28a84ec7..db1fc01a30 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -698,3 +698,55 @@ fn a_parametric_shape_kind_and_its_values_set_together() { assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); } } + +/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved +/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`. +/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and +/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept. +#[test] +fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() { + let mut s = session(); + select(&mut s, "shapeBuilder"); + assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session"); + select(&mut s, "selection"); + assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version"); + let load = |version: Option, saved: &Value| { + let mut prefs = Prefs::default().to_json(); + prefs["toolSettings"] = json!({ "shapeBuilder": saved }); + let fields = prefs.as_object_mut().unwrap(); + match version { + Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)), + None => fields.remove("toolSettingsVersion"), + }; + let mut next = session(); + next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap()); + next + }; + for (version, saved, want) in [ + (None, json!({"highlightFill": false}), "swatches"), + (None, json!({"pickColorFrom": "artwork"}), "swatches"), + (None, json!({"pickColorFrom": "swatches"}), "swatches"), + (Some(1), json!({"pickColorFrom": "artwork"}), "artwork"), + (Some(1), json!({"pickColorFrom": "swatches"}), "swatches"), + (Some(1), json!({"highlightFill": false}), "swatches"), + ] { + let mut next = load(version, &saved); + assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}"); + select(&mut next, "shapeBuilder"); + assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}"); + select(&mut next, "selection"); + assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}"); + } + // Artwork picked after the update, or in a session that started without saved settings, is + // kept at the next launch. + for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] { + select(&mut next, "shapeBuilder"); + next.set_tool_option("pickColorFrom", &json!("artwork")); + select(&mut next, "selection"); + let saved_text = serde_json::to_string(&next.prefs).unwrap(); + let mut later = session(); + later.apply_prefs(serde_json::from_str(&saved_text).unwrap()); + select(&mut later, "shapeBuilder"); + assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}"); + } +} diff --git a/crates/engine/src/tests/typearea.rs b/crates/engine/src/tests/typearea.rs index 9ada8b7194..7352c99420 100644 --- a/crates/engine/src/tests/typearea.rs +++ b/crates/engine/src/tests/typearea.rs @@ -123,7 +123,8 @@ fn transform_again_after_a_handle_drag_resizes_the_type_area_again() { assert!(near(r.origin(), Point::ZERO) && (r.width() - 640.0 / 3.0).abs() < 1e-6 && (r.height() - 250.0).abs() < 1e-6, "{r:?}"); let t = text(&s, id); assert_eq!(t.xf, Affine::translate((40.0, 40.0)), "the type isn't scaled"); - assert!(t.runs.iter().all(|r| r.style.size == 12.0)); + assert_eq!(t.plain_text(), STORY); + assert!(!t.runs.is_empty() && t.runs.iter().all(|r| r.style.size == 12.0), "{:?}", t.runs); } #[test] diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 0d1d6b50a8..656a5689f8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -197,6 +197,10 @@ fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { let dithered = file(&mut s, p.clone()); let [left, right] = opaque_halves(&pixels(&dithered)); assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if method == "pattern" { + // The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%. + assert_eq!([left, right], [0.25, 0.75], "{format}"); + } if format == "gif" { assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); } diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index d455f6ad2f..29d5ccb6ff 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1367,6 +1367,7 @@ fn distort_refuses_corners_type_and_symbol_instances_cannot_follow() { let want = [(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height())); s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap(); let got = drawn_corners(&s, id); + assert_eq!(got.len(), 4, "{got:?}"); assert!(got.iter().zip(want).all(|(g, w)| g.distance(w) < 1e-3), "{got:?} against {want:?}"); } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 422caab5ec..94f72f6441 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -581,6 +581,7 @@ impl Session { } } } + prefs.mark_tool_settings_current(); } /// Keep the active tool's persistent options for the next time it, or a tool sharing them, is diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 67d9b82f76..bcc712e844 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -30,17 +30,27 @@ fn no_panic(r: Result) -> Result Option { + probe_and_compare(fx, id, params, false).0 +} + +/// Run one call as [`probe`] does, returning its failure description, and with `compare`, also +/// `id params [fixture]` when the call changed the session's [`tool_edit_state`], panic or not. +fn probe_and_compare(fx: Fixture, id: &str, params: &Value, compare: bool) -> (Option, Option) { let mut s = fx.session(); + let before = compare.then(|| tool_edit_state(&s)); let r = catch_quiet(|| no_panic(s.execute(id, params))); - match r { + let changed = before.filter(|b| tool_edit_state(&s) != *b).map(|_| format!("{id} {params} [{fx:?}]")); + let failure = match r { Err(msg) => Some(format!("PANIC {id} {params} [{fx:?}]: {msg}")), Ok(_) => { if s.in_interaction() { - return Some(format!("{id} {params} [{fx:?}]: left an interaction open")); + Some(format!("{id} {params} [{fx:?}]: left an interaction open")) + } else { + check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - } + }; + (failure, changed) } #[test] @@ -223,31 +233,43 @@ fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { cases } +/// Every command with every junk case in every fixture: no panic, no interaction left open and no +/// broken invariant ([`probe`]). In `Single` and `Multi`, every command that runs at once while the +/// active tool computes an edit on another thread (it does not `waits_for_tool_edit`) also leaves +/// the documents' revisions and selections, the active document and the current paint as they were +/// ([`tool_edit_state`]), as `commands_that_do_not_wait_for_a_tool_edit_change_no_document` checks +/// for the cases that turn each option on and off. #[test] fn every_command_with_junk_params() { let dir = vectorcraft_testkit::TempDir::new("sweep"); let path = safe_path(&dir); let mut failures = vec![]; + let mut changed = vec![]; let mut calls = 0usize; for fx in Fixture::ALL { for c in command_specs() { + let compare = matches!(fx, Fixture::Single | Fixture::Multi) && !vectorcraft_engine::waits_for_tool_edit(c.id); let cases = junk_cases(c, &path); for p in &cases { calls += 1; - if let Some(f) = probe(fx, c.id, p) { - failures.push(f); - } + let (failure, change) = probe_and_compare(fx, c.id, p, compare); + failures.extend(failure); + changed.extend(change); } } } assert!(calls > 5_000, "only {calls} calls"); failures.sort(); failures.dedup(); + changed.sort(); + changed.dedup_by(|a, b| a.split(' ').next() == b.split(' ').next()); assert!( - failures.is_empty(), - "{} failures (of {calls} calls):\n{}", + failures.is_empty() && changed.is_empty(), + "{} failures (of {calls} calls):\n{}\n{} commands change a document without waiting for a tool edit:\n{}", failures.len(), - failures.iter().take(60).cloned().collect::>().join("\n") + failures.iter().take(60).cloned().collect::>().join("\n"), + changed.len(), + changed.join("\n") ); } @@ -262,10 +284,11 @@ fn tool_edit_state(s: &Session) -> ToolEditState { (docs, s.active_index(), s.paint.clone()) } -/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and -/// off, with a string under a file or folder key replaced by a location inside `path`'s folder. -fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { - let mut cases = junk_cases(c, path); +/// The params the tool-edit sweep sends `c` beyond its junk cases, which the junk sweep checks: +/// each documented key turned on and off, with a string under a file or folder key replaced by a +/// location inside `path`'s folder. +fn option_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = vec![]; for k in command_param_keys(c) { for v in [json!(true), json!(false), json!(1), json!("on")] { cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) })); @@ -333,7 +356,7 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { } } let mut cases = junk_params_for_command(c, &path); - cases.extend(tool_edit_cases(c, &path)); + cases.extend(option_cases(c, &path)); cases.extend(serializable_cases(c, &path)); for p in &cases { let Some(o) = p.as_object() else { continue }; @@ -485,8 +508,9 @@ fn sweep_cases_send_the_file_keys_of_the_command_catalog() { /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, -/// with `{}`, junk params and params that turn its options on and off: the edit, computed for the -/// document as it was, still applies after it. +/// with params that turn its options on and off ([`option_cases`]; `every_command_with_junk_params` +/// checks the same with the junk cases): the edit, computed for the document as it was, still +/// applies after it. #[test] fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let dir = vectorcraft_testkit::TempDir::new("sweep"); @@ -494,7 +518,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { - let cases = tool_edit_cases(c, &path); + let cases = option_cases(c, &path); for p in &cases { let mut s = fx.session(); let before = tool_edit_state(&s); @@ -538,6 +562,8 @@ fn structured_junk() { ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), + ("addon.select.editPointsOnly", json!({"segmentEnds": "yes"})), + ("addon.select.editPointsOnly", json!({"segmentEnds": [true], "ids": [2, u64::MAX]})), ("links.relink", json!({"scope": "each", "paths": [{"ids": [2, u64::MAX, -1, "x"], "path": ""}, null, 7, {"path": [1]}]})), ("links.relink", json!({"scope": ["all"], "path": "/no/such/file.png", "ids": {"a": 1}})), ("links.relink", json!({"scope": "missingInFolder", "path": "", "folder": [], "paths": "x"})), @@ -653,6 +679,7 @@ fn structured_junk() { ("perspective.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": -1e9, "plane": "left", "copy": true})), ("perspective.transform", json!({"matrix": [1, 0, 0, 1, 1e300, 0], "plane": "left"})), ("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "big": true, "copy": true})), + ("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "fine": true})), ("perspective.plane.move", json!({"plane": "ground", "offset": 1e308, "objects": "copy"})), ("perspective.plane.move", json!({"plane": "left", "by": -1e7, "objects": "move"})), ("perspective.plane.move", json!({"plane": "none", "offset": 0})), @@ -805,6 +832,9 @@ fn structured_junk() { ("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})), ("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})), ("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})), + ("addon.color.randomFill", json!({"seed": u64::MAX})), + ("addon.color.randomFill", json!({"scheme": "gray", "min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), + ("addon.color.randomFill", json!({"scheme": "tint", "swatch": "[Registration]", "min": 100, "max": 0, "seed": 1e308, "ids": []})), ("effect.apply", json!({"effect": "no.such.effect"})), ("effect.remove", json!({"index": 99})), ("effect.remove", json!({"indices": [0, 99, u64::MAX]})), @@ -1007,6 +1037,8 @@ fn structured_junk() { ("addon.arrange.match", json!({"source": "key", "rotate": true})), ("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), + ("addon.arrange.groupRows", json!({"direction": "column"})), + ("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), ("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})), @@ -1015,6 +1047,10 @@ fn structured_junk() { ("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})), ("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})), ("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})), + ("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})), + ("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})), + ("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})), + ("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})), ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9ff294a878..c6f02b9240 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -929,7 +929,20 @@ fn mutate_text(src: &str, cut: usize, edits: &[(usize, char)]) -> String { fn svg_type_shifted_two_billion_points_exports_to_pdf() { let svg = r#"f"#; let d = vectorcraft_svg::import(svg).unwrap(); - assert!(vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).is_ok()); + // The type opens with its shift, so the export below meets a glyph that far out. + let mut shifts = Vec::new(); + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + shifts.extend(t.runs.iter().map(|r| r.style.baseline_shift)); + } + }); + assert!(shifts.iter().any(|&s| s.abs() > 2e9), "baseline shifts read: {shifts:?}"); + let pdf = vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).unwrap(); + // The PDF leaves the type out: reading it back finds no type. + let back = vectorcraft_pdf::import(&pdf).unwrap(); + let mut text = 0; + back.walk(|n| text += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)))); + assert_eq!(text, 0, "type left out of the page"); } proptest! { @@ -8630,6 +8643,16 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() { let stream = canvas_stream(vec![with_effects(rectangle(10, (0.0, 0.0), (3_276_800.0, 50.0)), vec![shadow()])]); let bytes = affinity_sample_file(&stream, None); let doc = vectorcraft_engine::cmd::fileio::load("long.af", &bytes).unwrap().doc; + // The shape opens whole, with its shadow, so the exports below draw the shadow that far out. + let mut shadowed = Vec::new(); + doc.walk(|n| { + if n.appearance.effects.iter().any(|e| e.id == "stylize.dropShadow") { + shadowed.push(n.id); + } + }); + assert_eq!(shadowed.len(), 1, "one shape with a drop shadow"); + let width = doc.bounds_of(&shadowed, false).map(|r| r.width()); + assert!(width.is_some_and(|w| w > 3_000_000.0), "the shape is {width:?} pt wide"); survive("long shape", || Some(doc)).unwrap(); } diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 98fdbe6b23..a5bc28f24b 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() { assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings); } -#[test] -fn test_af_g_symbol_fill_is_white() { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af"); - let Ok(bytes) = std::fs::read(&path) else { - return; - }; - let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap(); - assert!(!loaded.preview_only, "{:?}", loaded.warnings); - let d = &loaded.doc; - // The visible "g41" group holds the "g" symbol (path43). - let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present"); - let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present"); - let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else { - panic!("path43 has no fill: {:?}", path43.appearance); - }; - assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint); +/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`. +fn recolored(visible: bool, lightness: f64) -> F { + let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0)); + let recolor = F::Def( + 20, + vec![tag(b"RcRA")], + vec![ + (tag(b"Visi"), F::Bool(visible)), + (tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])), + ], + ); + if let F::Def(_, _, fields) = &mut node { + fields.push((tag(b"AdCh"), F::Shared(vec![recolor]))); + } + node +} + +fn first_fill(n: &Node) -> Paint { + let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) }; + fill.paint.clone() +} + +#[test] +fn attached_recolor_adjustments_recolor_the_shape() { + // Lightness 1 recolors to white. + let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None)); + assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings); + let rect = named(&loaded.doc, "Magenta box"); + assert!(rect.appearance.effects.is_empty()); + assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0))); + // Lightness 0.5 at hue 0 and full saturation is pure red. + let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc; + let [r, g, b, a] = pixel(&d, 25, 25); + assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]); + // A hidden adjustment leaves the shape as it is. + let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc; + assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0))); } diff --git a/crates/engine/tests/it/affinity_local.rs b/crates/engine/tests/it/affinity_local.rs index 54df4a4612..30ab6d2163 100644 --- a/crates/engine/tests/it/affinity_local.rs +++ b/crates/engine/tests/it/affinity_local.rs @@ -2,7 +2,7 @@ //! recursively) opens as editable art, and each artboard is compared with the thumbnail Affinity //! stored in the file. Reports the mean difference per artboard (0–255, both on white); with //! `AFFINITY_SAMPLES_OUT` set, writes each board's thumbnail crop and render side by side there. -//! Skipped when `AFFINITY_SAMPLES` is unset (as in CI). +//! Ignored by default; run it with `--ignored` and `AFFINITY_SAMPLES` set. use std::path::{Path, PathBuf}; @@ -28,8 +28,9 @@ fn on_white(p: &[u8]) -> [f64; 3] { } #[test] +#[ignore = "local samples: set AFFINITY_SAMPLES to a folder of Affinity documents"] fn local_affinity_documents_render_like_their_thumbnails() { - let Some(root) = std::env::var_os("AFFINITY_SAMPLES").map(PathBuf::from) else { return }; + let root = PathBuf::from(std::env::var_os("AFFINITY_SAMPLES").expect("AFFINITY_SAMPLES names the folder of documents to check")); let out = std::env::var_os("AFFINITY_SAMPLES_OUT").map(PathBuf::from); let mut paths = Vec::new(); files(&root, &mut paths); diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/it/blend_render_consistency.rs similarity index 99% rename from crates/engine/tests/blend_render_consistency.rs rename to crates/engine/tests/it/blend_render_consistency.rs index fdc2fb3b93..fa69885ad7 100644 --- a/crates/engine/tests/blend_render_consistency.rs +++ b/crates/engine/tests/it/blend_render_consistency.rs @@ -1,5 +1,4 @@ //! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index bad590987d..1379cc0683 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -476,6 +476,7 @@ fn turned_horizontal_dimensions_stay_horizontal() { let mut ys = [d.a.y.round(), d.b.y.round()]; ys.sort_by(f64::total_cmp); assert_eq!(ys, [180.0, 280.0]); + assert_eq!(path_ends(&s, id)[2].len(), 2, "{:?}", path_ends(&s, id)); assert!(path_ends(&s, id)[2].iter().all(|(_, y)| (y - 130.0).abs() < 1e-6), "{:?}", path_ends(&s, id)); let line = run(&mut s, "shape.line", json!({"x1":100,"y1":400,"x2":200,"y2":400}))["id"].as_u64().unwrap(); let anchor = |anchor: u64| json!({"node":line,"subpath":0,"anchor":anchor}); diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs similarity index 99% rename from crates/engine/tests/direct_handle_mirror.rs rename to crates/engine/tests/it/direct_handle_mirror.rs index 30326d8e74..bfe8db75a0 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -1,5 +1,4 @@ //! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId}; diff --git a/crates/engine/tests/ellipse_drag_anchors.rs b/crates/engine/tests/it/ellipse_drag_anchors.rs similarity index 99% rename from crates/engine/tests/ellipse_drag_anchors.rs rename to crates/engine/tests/it/ellipse_drag_anchors.rs index afce996136..1e278505ed 100644 --- a/crates/engine/tests/ellipse_drag_anchors.rs +++ b/crates/engine/tests/it/ellipse_drag_anchors.rs @@ -1,5 +1,4 @@ //! Ellipse arrow keys edit the anchor count of the shape actually being dragged. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeId}; diff --git a/crates/engine/tests/eraser_open_fill.rs b/crates/engine/tests/it/eraser_open_fill.rs similarity index 99% rename from crates/engine/tests/eraser_open_fill.rs rename to crates/engine/tests/it/eraser_open_fill.rs index a0ab760660..a5f6e60956 100644 --- a/crates/engine/tests/eraser_open_fill.rs +++ b/crates/engine/tests/it/eraser_open_fill.rs @@ -1,6 +1,4 @@ //! Fill-only open-path Eraser regressions through the public engine and CPU renderer. -// Integration tests may unwrap and panic on failure (AGENTS.md). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; diff --git a/crates/engine/tests/group3_reference.rs b/crates/engine/tests/it/group3_reference.rs similarity index 100% rename from crates/engine/tests/group3_reference.rs rename to crates/engine/tests/it/group3_reference.rs diff --git a/crates/engine/tests/it/lossy_overwrite.rs b/crates/engine/tests/it/lossy_overwrite.rs index 559e45a33e..27ad030b15 100644 --- a/crates/engine/tests/it/lossy_overwrite.rs +++ b/crates/engine/tests/it/lossy_overwrite.rs @@ -76,10 +76,18 @@ fn a_file_the_import_left_things_out_of_is_not_written_over_unasked() { fn a_file_the_import_read_whole_is_written_over_as_before() { let d = dir("b"); let src = d.join("plain.eps"); - std::fs::write(&src, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 1 0 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto closepath fill\nshowpage\n%%EOF\n").unwrap(); + let original = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 1 0 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto closepath fill\nshowpage\n%%EOF\n"; + std::fs::write(&src, original).unwrap(); let mut s = Session::new(); - s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + let opened = s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + assert_eq!(opened["warnings"], json!([]), "{opened}"); s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "eps" })).unwrap(); + let written = std::fs::read(&src).unwrap(); + assert_ne!(written, original.as_bytes(), "the export wrote over the file"); + let mut again = Session::new(); + again.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + let doc = &again.doc().unwrap().doc; + assert!(doc.layers.iter().any(|l| l.children().is_some_and(|c| !c.is_empty())), "the square is in the file written"); std::fs::remove_dir_all(d).ok(); } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ff4a5c22ab..2be85215bb 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -12,13 +12,18 @@ mod affinity_local; mod align_automatic_reference; mod artboard_click; mod beyond_canvas; +mod blend_render_consistency; mod clear_commands; mod compound_attributes; mod copy_direct_selection; mod delete_path_pieces; mod dimensions; +mod direct_handle_mirror; +mod ellipse_drag_anchors; +mod eraser_open_fill; mod eyedropper_sources; mod find_replace_paras; +mod group3_reference; mod inline_text; mod js_lexer_vs_scriptcheck; mod known_bugs; @@ -27,12 +32,16 @@ mod model_based; mod param_keys; mod paste_many; mod pasted_clipping_path; +mod path_fill_hits; mod pen_click_after_smooth; mod pen_endpoint_picking; mod pen_rubber_band; +mod pen_space_handle; +mod preflight; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; +mod scissors_snap; mod script_host_vs_scriptcheck; mod selection_commands; mod several_handles; diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index fb30bf3c5c..7e80c1aedc 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -170,7 +170,8 @@ fn effect_params_no_longer_taken_still_replay_and_open() { } /// An effect's `color` that the effect can't read (a string `Color::from_hex` doesn't read, an -/// `[r, g, b]` without three numbers, an object that isn't a color, `null`) is refused by +/// `[r, g, b]` without three numbers, an object that isn't a color, `null`, a color with a component +/// too large to store) is refused by /// `effect.apply`, `appearance.addEffect` and `effect.setParams` themselves, not only by the check, /// and the document and its undo history stay as they were. The forms the effect reads pass. A /// document saved with an unreadable color still opens with it. @@ -186,7 +187,16 @@ fn an_effect_color_it_cannot_draw_is_refused() { }; let before = state(&s); let why = "`color` must be a #rrggbb color"; - for bad in [json!("not-a-color"), json!("#ff00"), json!([1, 0]), json!(["#ff0000", 0, 0]), json!({"gray": 50}), json!(null)] { + for bad in [ + json!("not-a-color"), + json!("#ff00"), + json!([1, 0]), + json!(["#ff0000", 0, 0]), + json!({"gray": 50}), + json!(null), + json!([1e300, 0, 0]), + json!({"model": "rgb", "r": 0, "g": 1e300, "b": 0}), + ] { for (cmd, params) in [ ("effect.setParams", json!({"index": 0, "params": {"color": bad}})), ("effect.apply", json!({"effect": "stylize.outerGlow", "params": {"color": bad}})), diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/it/path_fill_hits.rs similarity index 99% rename from crates/engine/tests/path_fill_hits.rs rename to crates/engine/tests/it/path_fill_hits.rs index f8dfebafaf..28ab79e36b 100644 --- a/crates/engine/tests/path_fill_hits.rs +++ b/crates/engine/tests/it/path_fill_hits.rs @@ -1,5 +1,4 @@ //! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/pen_space_handle.rs b/crates/engine/tests/it/pen_space_handle.rs similarity index 99% rename from crates/engine/tests/pen_space_handle.rs rename to crates/engine/tests/it/pen_space_handle.rs index 5e37ca8a11..9bb8a0b8c8 100644 --- a/crates/engine/tests/pen_space_handle.rs +++ b/crates/engine/tests/it/pen_space_handle.rs @@ -1,6 +1,4 @@ //! Pen lends Direct Selection for one handle gesture; Space repositions that handle's owner. -// Integration tests may unwrap and panic (AGENTS.md, Robustness). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/it/preflight.rs similarity index 98% rename from crates/engine/tests/preflight.rs rename to crates/engine/tests/it/preflight.rs index e656596d71..5dcfddf7b2 100644 --- a/crates/engine/tests/preflight.rs +++ b/crates/engine/tests/it/preflight.rs @@ -1,5 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - //! Production preflight must find actual delivery problems and clear them after repairs. use serde_json::{Value, json}; @@ -211,7 +209,9 @@ fn preflight_resource_font_finding_locates_its_instance() { s.execute("symbol.new", &json!({ "name": "Label" })).unwrap(); let r = check(&mut s); let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap(); - assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}"); + let ids = f["ids"].as_array().unwrap(); + assert!(!ids.is_empty(), "the finding names where the font is used: {r}"); + assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}"); } struct Folder(std::path::PathBuf); diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/it/scissors_snap.rs similarity index 99% rename from crates/engine/tests/scissors_snap.rs rename to crates/engine/tests/it/scissors_snap.rs index 6d12bd6457..b81ac05bab 100644 --- a/crates/engine/tests/scissors_snap.rs +++ b/crates/engine/tests/it/scissors_snap.rs @@ -1,5 +1,4 @@ //! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d8b6c989d5..6b8965dd7f 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,14 +37,20 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"), ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), + ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), + ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not /// change anything outside it. The document model (`app`, its classes and the enumerations) acts on -/// the open documents; `Document.saveAs` and `close` throw "not available yet". +/// the open documents; `Document.close` closes a document, and saves it to its own file only when it +/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and +/// `Document.path` only name its file and folder. `app.open` reads the file it is given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), ("Window.", "alert confirm length prompt prototype"), @@ -91,8 +97,9 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ - executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \ - undo unloadAction unloadAction=", + executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \ + selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \ + userInteractionLevel=", ), ("DocumentPreset.", "prototype"), ( @@ -103,18 +110,18 @@ const INSIDE: &[(&str, &str)] = &[ toString transparencyGrid transparencyGrid= typename units units= width width=", ), ("Documents.", "prototype"), - ("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"), + ("Documents.prototype.", "add addDocument addDocumentNoUI constructor getByName index length parent toString typename"), ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + "activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \ defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \ defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \ defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \ defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ - defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \ - groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \ - rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \ + defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \ + groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \ + rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), @@ -184,6 +191,140 @@ const INSIDE: &[(&str, &str)] = &[ ("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"), ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + // The enumerations of saving, exporting and opening. + ( + "", + "ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \ + EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \ + PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \ + SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel", + ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \ + AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \ + JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \ + JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \ + CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), + ( + "Compatibility.", + "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ + ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3", + ), + ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), + ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), + ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), + ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), + ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), + ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), + ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The print option classes and the enumerations of printing. + ( + "", + "FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \ + PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \ + PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \ + PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \ + Printer PrinterPostScriptLevelEnum PrintingBounds", + ), + ("Printer.", "prototype"), + ("Printer.prototype.", "constructor name printerInfo printerInfo= typename"), + ("PrintOptions.", "prototype"), + ( + "PrintOptions.prototype.", + "PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \ + constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \ + flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \ + paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename", + ), + ("PrintJobOptions.", "prototype"), + ( + "PrintJobOptions.prototype.", + "artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \ + designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \ + printAsBitmap printAsBitmap= reversePages reversePages= typename", + ), + ("PrintColorManagementOptions.", "prototype"), + ("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"), + ("PrintColorSeparationOptions.", "prototype"), + ( + "PrintColorSeparationOptions.prototype.", + "colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \ + overPrintBlack overPrintBlack= typename", + ), + ("PrintCoordinateOptions.", "prototype"), + ( + "PrintCoordinateOptions.prototype.", + "constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \ + position position= tiling tiling= typename verticalScale verticalScale=", + ), + ("PrintFlattenerOptions.", "prototype"), + ( + "PrintFlattenerOptions.prototype.", + "clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \ + convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \ + gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename", + ), + ("PrintFontOptions.", "prototype"), + ("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"), + ("PrintPageMarksOptions.", "prototype"), + ( + "PrintPageMarksOptions.prototype.", + "bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \ + pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \ + trimMarksWeight trimMarksWeight= typename", + ), + ("PrintPaperOptions.", "prototype"), + ("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="), + ("PrintPostScriptOptions.", "prototype"), + ( + "PrintPostScriptOptions.prototype.", + "binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \ + forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \ + postScriptLevel= shadingResolution shadingResolution= typename", + ), + ("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"), + ("PageMarksTypes.", "Japanese Roman"), + ("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"), + ("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"), + ("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"), + ("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"), + ("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"), + ("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"), + ("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"), + ( + "PrintPosition.", + "TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \ + TRANSLATETOPLEFT TRANSLATETOPRIGHT", + ), + ("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"), + ("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"), + ("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"), ( "", "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ @@ -314,10 +455,11 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// other than `PathItem`, and the color classes. +/// other than `PathItem`, the color classes, and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ - SymbolItem cmykColor"; + SymbolItem cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \ + PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index be06539537..0a6e438a75 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -533,7 +533,8 @@ fn seams_against_supersampled(d: &Document, image: &vectorcraft_render::Rendered /// opacity once over the surface. Inflate seen straight on, one layer of facets, has no alpha off, and /// in opaque fills no RGB channel more than 3 levels off. Inflate turned so facets narrow to slivers /// at the edges, and Revolve with a cap over its body, draw facets over other facets, and have no -/// alpha off. +/// alpha off. In the turned Inflate's opaque solid fill, each facet and its seam cover an edge pixel +/// once together, so at most one RGB channel is more than 3 levels off, by no more than 4. #[test] fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let lights = json!([ @@ -556,20 +557,21 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let (mut s, _) = setup("threeD.inflate"); let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":rotation.0,"rotationY":rotation.1}}); s.execute("effect.setParams", &change).unwrap(); - cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0))); + cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0), rotation == (50, 35))); } let (mut s, _) = capped_profile(); s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap(); - cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false)); + cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false, false)); let mut failures = vec![]; - for (name, mut s, fills, one_layer) in cases { + for (name, mut s, fills, one_layer, turned) in cases { for fill in fills { s.execute("paint.setFill", &fill).unwrap(); let image = render(doc(&s)); let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); assert!(measured > 2_000, "{name} {fill}: {measured} pixels inside"); let opaque = !fill.to_string().contains("opacity"); - if holes > 0 || (one_layer && opaque && color > 0) { + let edges_once = turned && fill.get("color").is_some(); + if holes > 0 || (one_layer && opaque && color > 0) || (edges_once && (color > 1 || max > 4)) { failures.push(format!( "{name} {fill}: of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" )); @@ -579,29 +581,6 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { assert!(failures.is_empty(), "{failures:#?}"); } -/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two -/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its -/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by -/// no more than 4, and no alpha is off. -#[test] -fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() { - let lights = json!([ - {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, - {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} - ]); - let (mut s, _) = setup("threeD.inflate"); - let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}}); - s.execute("effect.setParams", &change).unwrap(); - s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap(); - let image = render(doc(&s)); - let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); - assert!(measured > 2_000, "{measured} pixels inside"); - assert!( - holes == 0 && color <= 1 && max <= 4, - "of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" - ); -} - /// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at /// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the /// live art. diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 11a42a6f90..9f77d86ec4 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -88,6 +88,66 @@ fn path_of(p: &std::path::Path) -> String { p.to_string_lossy().into_owned() } +#[test] +fn scripted_open_converts_importer_output_to_the_requested_color_space() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT)); + let dir = tmp_dir("scriptcolorspace"); + s.attach_script_data(dir.join("settings/Script Data")); + let file = dir.join("drawing.tscmyk"); + std::fs::write(&file, b"importer input").unwrap(); + let script = dir.join("main.jsx"); + let path = serde_json::to_string(&file.to_string_lossy()).unwrap(); + for (argument, mode) in [ + ("", vectorcraft_doc::ColorMode::Rgb), + (", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk), + (", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb), + ] { + std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap(); + let count = s.documents().len(); + let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap(); + assert_eq!(s.documents().len(), count + 1); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.color_mode, mode, "{argument}: {out}"); + let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap(); + if mode == vectorcraft_doc::ColorMode::Cmyk { + assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"])); + } else { + assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"])); + } + } + let _ = std::fs::remove_dir_all(dir); +} + +/// A script's PDF open options are refused for a file the named importer reads, which is given +/// only the params, even when the file's extension is a PDF one. +#[test] +fn scripted_pdf_open_options_are_refused_for_an_importer() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT)); + let dir = tmp_dir("scriptpdfoptions"); + s.attach_script_data(dir.join("settings/Script Data")); + let file = dir.join("x.ai"); + std::fs::write(&file, b"importer input").unwrap(); + let script = dir.join("main.jsx"); + let path = serde_json::to_string(&file.to_string_lossy()).unwrap(); + for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] { + std::fs::write( + &script, + format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"), + ) + .unwrap(); + let count = s.documents().len(); + let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})); + let text = format!("{out:?}"); + assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}"); + assert_eq!(s.documents().len(), count, "{option}"); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_importer_adds_a_read_only_format_while_it_is_installed() { let mut s = Session::new(); diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 9e8a77e5dc..8e2a46c852 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -873,6 +873,7 @@ mod tests { } r.entry(&[V::Num(0.0), name("E")], Affine::IDENTITY); let mesh = r.one_mesh().unwrap(); + assert_eq!(mesh.points.len(), 9, "{mesh:?}"); assert!(mesh.points.iter().all(|q| q.p.x.is_finite() && q.p.y.is_finite() && q.handles.iter().all(|h| h.x.is_finite() && h.y.is_finite()))); } @@ -962,6 +963,7 @@ mod tests { assert!(!reader.unread, "{with_opacity} {data_first}"); let mesh = reader.one_mesh().unwrap(); let want = if with_opacity { 0.25 } else { 1.0 }; + assert_eq!(mesh.points.len(), 4, "{with_opacity} {data_first}: {mesh:?}"); assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}"); } } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 17d9896ab9..8a29eec63e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -248,6 +248,9 @@ pub struct Structure { /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an /// id two objects have. pub xml_ids: HashMap>, + /// The group of a styled text object and its look, by the text object's slot id. The group, + /// not the type in it, is hidden or locked where the text object was. + pub text_looks: HashMap, /// The objects the variable library binds to its variables, by their XML ids: the importer /// binds those it keeps. pub bindings: Vec, @@ -664,8 +667,9 @@ struct Reader<'a> { ruler_guides: HashMap, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet, - /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. - text_looks: HashSet, + /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look, each + /// with the text object's slot id. + text_looks: HashMap, /// Objects followed by samples of the pen (`(…) Xt n XD`), which aren't read: such an object /// whose style has a Calligraphic brush that varies with the pen keeps its drawn look (see /// [`Self::style_marker`]). @@ -911,7 +915,7 @@ impl<'a> Reader<'a> { looks: HashSet::new(), ruler_guides: HashMap::new(), compound_groups: HashSet::new(), - text_looks: HashSet::new(), + text_looks: HashMap::new(), pen_samples: HashSet::new(), group_ended: false, mesh_ended: false, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 20102b29c4..ec14b864d9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1485,6 +1485,7 @@ impl<'a> Reader<'a> { canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, + text_looks: self.text_looks.into_iter().map(|(group, slot)| (slot, group)).collect(), bindings, bindings_skipped, warnings, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 881d3b3703..f5e6841c26 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -378,7 +378,7 @@ impl<'a> Reader<'a> { } } "Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0), - "A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0), + "A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0), "XW" => self.state_marker(&vals, hidden), // Gradients. "Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names), @@ -822,7 +822,7 @@ impl<'a> Reader<'a> { // The look is a group of paths, or one image where an effect (a blur, a shadow) rasterizes it. if !self.hidden_ids.contains(&object.id) || self.hidden_ids.contains(&look.id) != hidden - || self.text_looks.contains(&look.id) + || self.text_looks.contains_key(&look.id) || !matches!(look.kind, NodeKind::Group { clip: false, .. } | NodeKind::Image(_)) { return; @@ -978,10 +978,15 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); + let (visible, locked, slot) = (object.visible, object.locked, object.id); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); + object.visible = true; + object.locked = false; let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; - self.text_looks.insert(group.id); + group.visible = visible; + group.locked = locked; + self.text_looks.insert(group.id, slot); if let Some(f) = self.frames.last_mut() { f.children.push(group); } @@ -2212,7 +2217,8 @@ mod tests { let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); assert_eq!(ids, ["warp.arc"]); - assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // The image's own look: none of the look's fills and strokes. + assert!(ap.items.is_empty(), "{ap:?}"); // Not on a path, nor on an image with an opacity mask. assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); let mut masked = image.clone(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 28e31e52c6..9ef4cbc840 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -291,6 +291,7 @@ fn object_tags_without_an_object_before_them_tag_nothing() { let doc = read7(&layer7("L", &body)).doc; let mut all = art(&doc); all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::>()); + assert!(!all.is_empty(), "{body}: no art"); assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); } for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { @@ -12411,6 +12412,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain +/// intrinsic visibility, so showing the group makes the inner artwork visible. +#[test] +fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() { + let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect(); + let object = format!( + "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n", + rect_path(20.0, 18.0, 100.0, 62.0) + ); + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "wrapper group created: {a:#?}"); + let group = &a[0]; + assert!(!group.visible, "wrapper group must inherit hidden state"); + assert!(group.locked, "wrapper group must inherit locked state"); + let children = group.children().expect("must be a group of look and text"); + assert_eq!(children.len(), 2); + for child in children { + assert!(child.visible, "inner child must retain intrinsic visibility"); + assert!(!child.locked, "inner child must not be locked"); + } + let mut shown = (**group).clone(); + shown.visible = true; + for child in shown.children().unwrap() { + assert!(child.visible, "inner child remains visible when parent group is shown"); + } +} + /// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: /// the side of the section with y up goes down the page with the rotation at 0° to the page, and /// to the right of the path's direction when the rotation follows the path. A rotation turns the diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index a8146e679e..596e0d8ac6 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -43,7 +43,7 @@ use super::ate::{Story, Texts}; mod build; pub(super) mod compare; -mod layers; +pub(super) mod layers; mod plan; mod slots; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 5b0eb51a73..9daa57bfd8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -4,8 +4,8 @@ use super::compare::{ }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, - collect_slots, extent, few, fill_slots, letters, text_objects, words, + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, + TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words, }; use super::{ Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, @@ -350,6 +350,7 @@ pub(super) fn build_weighing( canvas_scale, symbols_own_size, xml_ids, + text_looks, bindings, bindings_skipped, warped_type, @@ -653,7 +654,7 @@ pub(super) fn build_weighing( None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); - bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &text_looks, &mut notes); if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { notes.push(ai::LINKED_PREVIEWS.to_string()); } @@ -731,7 +732,9 @@ fn to_placed_documents( /// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each /// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text /// object's slot: for a visibility variable every object that took the slot's place, for a text -/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// variable the one text object among them). A visibility variable binds a styled text object's +/// group with its look (`text_looks`, by slot) in place of the type: the group is what is hidden or +/// shown. An object is bound when it is of the variable's kind: /// type for a text variable, a linked image for an image variable, any object for a visibility /// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects /// on locked artboards keep their bindings. Graph variables and @@ -743,6 +746,7 @@ fn bind_variables( skipped: usize, ids: &std::collections::HashMap>, filled: &std::collections::HashMap, + text_looks: &std::collections::HashMap, notes: &mut Vec, ) { let mut skipped = skipped; @@ -753,7 +757,12 @@ fn bind_variables( let mut bound = vec![]; for b in bindings { let kind = doc.variables.variable(&b.variable).map(|v| v.kind); - let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + let target = b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()); + let target = match kind { + Some(VariableKind::Visibility) => target.map(|id| text_looks.get(&id).copied().unwrap_or(id)), + _ => target, + }; + let targets = match (target, kind) { (Some(id), Some(kind)) => match filled.get(&id) { Some(f) if kind == VariableKind::Visibility => f.objects.clone(), Some(f) => match f.text.as_slice() { @@ -1514,9 +1523,11 @@ fn slot_content( } // The page's type is matched with every text object whose type isn't made, and weighed against // where every made one draws: that has its limits (the slots of type that looks draw are within - // them, see `build_from`). + // them, see `build_from`). A file whose text document makes all but a few text objects is + // matched only with those few (#9176). let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count(); - if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + let shown = pages[0].len(); + if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS { return Err("it has too many text objects".into()); } let mut content = plan(infos, stories, made, template, to_doc, pages, notes); @@ -2817,7 +2828,7 @@ mod candidate_tests { bind("v_graph", "path"), ]; let mut notes = vec![]; - bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + bind_variables(&mut doc, &refs, 3, &ids, &filled, &Default::default(), &mut notes); let sorted = |mut v: Vec| { v.sort(); v diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index bbbacc1c4b..dcaa95a141 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -172,13 +172,19 @@ pub fn layered_ai_from( } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). - let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { + let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str, layers_read: bool| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); let (boards, active) = ai::artboards(&data, &mut board_names); if place_pages(&boards, active, &mut visible, unit) { read.absorb(board_names); } + // The editing data's locks, read again only here (and only when its layers could be read): + // the layers read below are spent on the editable document, which most files open as. + if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() { + let private_layers: Vec = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect(); + apply_private_layer_locks(&mut visible.layers, &private_layers); + } let have = visible.patterns.len(); let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); @@ -199,7 +205,9 @@ pub fn layered_ai_from( // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| { + let structure = structure.unwrap_or_else(|| read().map(Box::new)); + let layers_read = structure.is_ok(); + let built = structure.and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -230,7 +238,7 @@ pub fn layered_ai_from( all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::>()); (done, all, true) } - Err(why) => from_pdf_part(visible, warnings, &why), + Err(why) => from_pdf_part(visible, warnings, &why, layers_read), } } @@ -245,6 +253,78 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { }) } +/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states +/// without holding `Arc` references to the artwork tree. +#[derive(Clone, Debug, Default)] +pub(crate) struct LockTree { + pub name: Option, + pub locked: bool, + pub children: Vec, +} + +impl LockTree { + pub fn from_node(node: &Node) -> Self { + Self { + name: node.name.clone(), + locked: node.locked, + children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(), + } + } +} + +/// Match unique names between visible nodes and private lock trees. +fn unique_name_pairs>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> { + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_nodes.iter().enumerate() { + if let Some(name) = p.name.as_deref() { + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; + } + } + + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_nodes.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; + } + } + + let mut pairs = Vec::new(); + for (v_idx, vis) in vis_nodes.iter().enumerate() { + if let Some(name) = vis.name.as_deref() + && vis_names.get(name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(name) + { + pairs.push((v_idx, p_idx)); + } + } + pairs +} + +/// Apply lock states from private data layers to visible PDF layers. +pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { + // Only layers that are evidently the same one (a name unique on both sides) take its locks: one + // layer each is no evidence, since a PDF part without layers comes in on a layer named for its + // page, and the editing data it was set aside for may not be the art on it. + for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) { + apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); + } +} + +fn apply_node_locks(vis: &mut Node, priv_: &LockTree) { + if priv_.locked { + vis.locked = true; + } + let Some(vis_kids) = vis.children_mut() else { return }; + if vis_kids.is_empty() || priv_.children.is_empty() { + return; + } + + for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) { + apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]); + } +} + /// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, /// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` /// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 6d4799721e..f2dfba3377 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -154,8 +154,19 @@ pub(super) fn made_only( if looks && infos.len().saturating_mul(shown.len()) <= MAX_PAIRS { let spelled: Vec = content.iter().map(|c| if let Content::Made(node, ..) = c { spelling(&plain_text(node)) } else { String::new() }).collect(); - let made_type = |o: &[Arc]| covered(o, &content, |_| true) && has_made_words(o, &content, &spelled); + // Past the word searches, type where made type draws is taken to be that type. + let (mut checks, mut unchecked) = (WordChecks::new(), false); + let mut made_type = |o: &[Arc]| { + covered(o, &content, |_| true) + && has_made_words(o, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }) + }; let mut spare: Vec>> = shown.iter().filter(|o| !made_type(o)).cloned().collect(); + if unchecked { + note_unchecked(warn); + } fill_look_slots(infos, &mut content, &mut spare); for c in &content { if let Content::Page(parts) = c { @@ -173,7 +184,7 @@ pub(super) fn made_only( match see_page_type(&mut content, untaken) { Some(0) => {} Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), - None => warn.push(PAGE_TYPE_UNCHECKED.into()), + None => note_unchecked(warn), } drop_look_slots(infos, &mut content); fill_hidden(infos, stories, &mut content, hidden); @@ -274,17 +285,64 @@ fn fill_look_slots(infos: &[SlotInfo], content: &mut [Content], spare: &mut Vec< drop_look_slots(infos, content); } +/// How many more times a word of the page's type may be looked for in a text object's type. The +/// page's type is weighed against where every text object lies up to `MAX_PLACE_PAIRS` pairs, a box +/// against a box, but each text object a piece of it lies on can be searched for each of its words: +/// those searches are held to `MAX_PAIRS` of their own. +struct WordChecks(usize); + +impl WordChecks { + fn new() -> Self { + WordChecks(MAX_PAIRS) + } + + /// One more search, if any are left. + fn spend(&mut self) -> Option<()> { + self.0 = self.0.checked_sub(1)?; + Some(()) + } + + /// Are no searches left? + fn spent(&self) -> bool { + self.0 == 0 + } +} + /// Has made type that shows and draws where the page's text object `object` lies every word of it -/// ([`spelling`], each slot's in `spelled`), in any order? -fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String]) -> bool { - let Some(r) = extent(object) else { return true }; +/// ([`spelling`], each slot's in `spelled`), in any order? `None` once `checks` runs out before +/// that is known. +fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String], checks: &mut WordChecks) -> Option { + let Some(r) = extent(object) else { return Some(true) }; + if checks.spent() { + return None; + } let near: Vec<&String> = content .iter() .zip(spelled) .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) .map(|(_, s)| s) .collect(); - object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) + for w in object_words(object) { + let mut found = false; + for s in &near { + checks.spend()?; + if s.contains(w.as_str()) { + found = true; + break; + } + } + if !found { + return Some(false); + } + } + Some(true) +} + +/// Note once in `warn` that some of the page's type wasn't checked against the text objects. +fn note_unchecked(warn: &mut Vec) { + if !warn.iter().any(|w| w == PAGE_TYPE_UNCHECKED) { + warn.push(PAGE_TYPE_UNCHECKED.into()); + } } /// The text slots for type that a look draws and that have nothing have no type of their own to hold @@ -338,32 +396,78 @@ fn made_content(infos: &[SlotInfo], made: Vec>, laid: bool) -> Vec< /// it, as far as strokes round type reach) as type the page draws. How many of the page's text /// objects no made type takes, shown or not: none that holds a piece of the object has its words /// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`). +/// +/// The page can draw two text objects as one word: a word and a letter set apart from it (a swash +/// "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. A word +/// left that is the last word of one text object holding the piece joined to the first word of +/// another that holds it and draws after it, along the first one's lines, is theirs +/// ([`joined_by_two`]). fn see_page_type(content: &mut [Content], shown: &[Vec>]) -> Option { let texts = |o: &[Arc]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::>(); // Each object's pieces of type, and the words of them that no made type holding it has yet. let mut objects: Vec<(Vec, Vec, bool)> = shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect(); let pieces: usize = objects.iter().map(|o| o.0.len()).sum(); - if content.len().saturating_mul(pieces) > MAX_PAIRS { - return None; - } + let mut budget = MAX_PAIRS.checked_sub(content.len().checked_mul(pieces)?)?; let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9); - for c in content { - let Content::Made(node, region, seen) = c else { continue }; + // The made type holding each object, in order: where it draws and its words. + let mut holders: Vec>> = vec![vec![]; objects.len()]; + let mut seen_slots = Vec::new(); + for (slot, c) in content.iter().enumerate() { + let Content::Made(node, region, _) = c else { continue }; // Hidden made type has no region: where it draws, shown, is its own box. let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue }; - let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() }; - for (rects, words, held) in &mut objects { + let (spelled, holder) = match &node.kind { + NodeKind::Text(t) => { + let text = t.plain_text(); + let [a, b, ..] = t.xf.as_coeffs(); + (spelling(&text), Some(Arc::new((drawn.center(), (a, b), word_pieces(&text).map(spelling).filter(|w| !w.is_empty()).collect())))) + } + _ => (String::new(), None), + }; + for ((rects, words, held), by) in objects.iter_mut().zip(&mut holders) { if rects.iter().any(|r| holds(drawn, r)) { *held = true; - *seen |= region.is_some(); + if region.is_some() && seen_slots.last() != Some(&slot) { + seen_slots.push(slot); + } words.retain(|w| !spelled.contains(w.as_str())); + by.extend(holder.clone()); } } } + for ((_, words, _), by) in objects.iter_mut().zip(&holders) { + if !words.is_empty() && !by.is_empty() { + // Each unmatched word can visit every ordered pair of holders, plus the first-holder scan. + budget = budget.checked_sub(words.len().checked_mul(by.len())?.checked_mul(by.len().checked_add(1)?)?)?; + words.retain(|w| !joined_by_two(w, by)); + } + } + for slot in seen_slots { + if let Content::Made(_, _, seen) = &mut content[slot] { + *seen = true; + } + } Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count()) } +/// A made text object that holds a piece of the page's type: the centre of where it draws, the +/// way its lines run (the first column of its transform) and its words ([`spelling`]). +type Holder = (Point, (f64, f64), Vec); + +/// Is `word` (a [`spelling`]) the last word of one of `by` joined to the first word of another of +/// them that draws after it, along the first one's lines? Each part is a whole word of its text +/// object, so a piece is never made up of bits of words. +fn joined_by_two(word: &str, by: &[Arc]) -> bool { + by.iter().map(Arc::as_ref).any(|(at, (a, b), first)| { + let Some(head) = first.last().filter(|h| word.len() > h.len() && word.starts_with(h.as_str())) else { return false }; + let tail = &word[head.len()..]; + by.iter() + .map(Arc::as_ref) + .any(|(next, _, second)| (next.x - at.x) * a + (next.y - at.y) * b > 0.0 && second.first().is_some_and(|w| w == tail)) + }) +} + /// What goes into each of `infos`' slots when the file's text document can't make the type of every /// slot that shows: type made from the text document (`made`) where it can, else the page's type that /// the text document puts where the page has it, else the page's type in a copy that a layer's or @@ -392,9 +496,16 @@ pub(super) fn plan( let made_stories: std::collections::BTreeSet = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); let open: Vec = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); let owner = match_page_objects(infos, &lines, &open, shown); - // Where the made type that doesn't show lies, by slot. - let hidden_at: Vec<(usize, Rect)> = - infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Where the made type that doesn't show lies, and the letters of its lines (it has lines). + let hidden_at: Vec<(Rect, Vec)> = infos + .iter() + .zip(&made) + .enumerate() + .filter_map(|(k, (info, m))| { + let place = m.as_ref().filter(|_| !info.shown)?.1?; + Some((place, lines.get(k)?.as_ref()?.iter().map(|(text, _)| letters(text)).collect())) + }) + .collect(); // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box // stays that of type without a layout here: with text objects whose type isn't made stacked on // made type that has their words (the copies of an outlined heading), the page's pieces in the @@ -402,17 +513,34 @@ pub(super) fn plan( let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) - let hidden_type = |object: &[Arc]| { - let Some(r) = extent(object) else { return false }; + // `None` once `checks` runs out before that is known. + let hidden_type = |object: &[Arc], checks: &mut WordChecks| -> Option { + let Some(r) = extent(object) else { return Some(false) }; let texts: Vec> = object.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text())) } else { None }).collect(); - hidden_at.iter().any(|(k, place)| { - place.intersect(r).area() >= 0.5 * r.area().max(1e-9) - && lines.get(*k).and_then(Option::as_ref).is_some_and(|l| { - !texts.is_empty() - && texts.iter().all(|ws| !ws.is_empty() && ws.iter().all(|w| l.iter().any(|(text, _)| letters(text).contains(w.as_str())))) - }) - }) + if texts.is_empty() || texts.iter().any(Vec::is_empty) { + return Some(false); + } + for (place, l) in &hidden_at { + if place.intersect(r).area() < 0.5 * r.area().max(1e-9) { + continue; + } + let mut all = true; + 'words: for w in texts.iter().flatten() { + for text in l { + checks.spend()?; + if text.contains(w.as_str()) { + continue 'words; + } + } + all = false; + break; + } + if all { + return Some(true); + } + } + Some(false) }; // The letters and digits of each slot's made type that shows, in any script, in lower case. let spelled: Vec = content @@ -426,6 +554,12 @@ pub(super) fn plan( }) .collect(); let mut spare: Vec>> = vec![]; + // The word searches below are held to their own budget: past it, type where made type that shows + // draws is taken to be that type (made type is there either way), and type where only made type + // that doesn't show lies is spare type, as any type no text object takes: it goes into a slot + // or with another text object's type, else it is left out with a note (taken as the hidden + // type, it would be dropped unnoted). + let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { @@ -433,13 +567,28 @@ pub(super) fn plan( Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type draws, with its words, is that type as the page draws it (in - // another font, maybe, and in any script). - None if covered(object, &content, |_| true) && has_made_words(object, &content, &spelled) => {} - None if hidden_type(object) => {} - None => spare.push(object.clone()), + None => { + // What lies where made type draws, with its words, is that type as the page draws it + // (in another font, maybe, and in any script). + let theirs = covered(object, &content, |_| true) + && has_made_words(object, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }); + let hidden = !theirs + && hidden_type(object, &mut checks).unwrap_or_else(|| { + unchecked = true; + false + }); + if !theirs && !hidden { + spare.push(object.clone()); + } + } } } + if unchecked { + note_unchecked(warn); + } // The page's type that no made type takes is the spare type below. let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { @@ -554,3 +703,39 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{CharStyle, TextObject}; + + fn text(id: u64, s: &str) -> Node { + let style = CharStyle { size: 12.0, ..CharStyle::default() }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(100.0, 100.0), s, style)))) + } + + /// The page's type is searched for in every made text object that draws where it lies, word by + /// word: those searches stop when their budget runs out, saying they didn't finish, however many + /// made text objects lie there. A word is searched for only until a text object has it. + #[test] + fn word_searches_of_the_page_s_type_stop_when_their_budget_runs_out() { + let everywhere = Rect::new(-1e4, -1e4, 1e4, 1e4); + let slots = 50; + let content: Vec = (0..slots).map(|k| Content::Made(Box::new(text(k, "Other type")), Some(everywhere), false)).collect(); + let spelled: Vec = + content.iter().map(|c| if let Content::Made(n, ..) = c { spelling(&plain_text(n)) } else { String::new() }).collect(); + // A word no made type has is searched for in each of them. + let missing = vec![Arc::new(text(1000, "Alpha beta"))]; + let one_word_everywhere = slots as usize; + let mut short = WordChecks(one_word_everywhere - 1); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut short), None, "past the budget the answer isn't known"); + assert!(short.spent()); + let mut enough = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut enough), Some(false)); + // Words that the first made type has are found there, without searching the others. + let present = vec![Arc::new(text(1001, "other TYPE"))]; + let mut few = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true)); + assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0); + } +} diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 5be707fac7..006b8852b3 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20; /// kept as outlines and a node of the page's type. pub(super) const MAX_PAIRS: usize = 4_000_000; +/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by +/// where each lies (a box against a box, far cheaper than matching the page's type with a text +/// object's words, which [`MAX_PAIRS`] limits). +pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS; + /// `names` for a note: the first few, and how many more. pub(super) fn few(names: BTreeSet) -> String { const SHOWN: usize = 5; @@ -307,12 +312,6 @@ pub(super) fn fill_slots( .iter() .map(|p| { let mut p = reid(doc, p); - if !visible { - Arc::make_mut(&mut p).visible = false; - } - if locked { - Arc::make_mut(&mut p).locked = true; - } if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) { Arc::make_mut(&mut p).name = Some(name.clone()); } @@ -321,6 +320,7 @@ pub(super) fn fill_slots( .collect(); let mut text = vec![]; text_ids(&parts, &mut text); + let mut wrapped = false; // When the page draws each of them with no transparency, the slot's, or the slot's // combined with that of the objects around it, the slot's takes its place: on the one // part, or on a group of several when the slot has transparency. Otherwise every part @@ -342,9 +342,12 @@ pub(super) fn fill_slots( (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); + group.visible = visible; + group.locked = locked; (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = (state.0, state.1, state.2, state.3, shape); parts.push(Arc::new(group)); + wrapped = true; } } // A wrap object stays one: the page's parts of it in a group, when there are several. @@ -352,12 +355,25 @@ pub(super) fn fill_slots( if parts.len() > 1 { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; + group.locked = locked; parts.push(Arc::new(group)); + wrapped = true; } for p in &mut parts { Arc::make_mut(p).extras_mut().wrap = wrap; } } + if !wrapped { + for p in &mut parts { + let p = Arc::make_mut(p); + if !visible { + p.visible = false; + } + if locked { + p.locked = true; + } + } + } // One text object with the slot's appearance and transparency keeps its graphic style. if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref()) && linked.is_some() @@ -751,4 +767,93 @@ mod tests { let inner = nodes[0].children().unwrap()[0].id; assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] })); } + + /// A transparent slot wrapper group inherits hidden state while its inner children retain + /// their original visibility (both visible and intrinsically hidden), so showing the group + /// reveals only the intrinsically visible artwork. + #[test] + fn transparent_slot_wrapper_group_showing_reveals_inner_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + slot.opacity = 0.5; // see_through(n) == true -> transparent == true + + let part = |doc: &mut Document, x: f64, visible: bool| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) + }; + // Page run contains both a visible child and an intrinsically hidden child: + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)"); + assert!(group.locked, "wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); + + // Showing the group updates only the group node's visible field: + let mut shown = (**group).clone(); + shown.visible = true; + assert!(shown.visible); + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); + } + + /// A wrap slot wrapper group inherits hidden and locked states without overwriting children's + /// original visibility flags when a page run contains both visible and intrinsically hidden children. + #[test] + fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true }; + slot.extras_mut().wrap = Some(wrap); + + let part = |doc: &mut Document, x: f64, visible: bool| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) + }; + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrap wrapper group must inherit hidden state"); + assert!(group.locked, "wrap wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); + + let mut shown = (**group).clone(); + shown.visible = true; + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); + } } diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index ff3b3382d3..4caf968271 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -64,8 +64,12 @@ fn type42_descendants_draw_their_own_glyphs() { } // The H, then the I one H's width along; both stand on the baseline, a cap height tall. let (bh, bi) = (bounds(paths[0]), bounds(paths[1])); - assert!((bh.x0 - 10.0).abs() < 8.0 && bh.width() > 20.0 && bh.width() < 50.0 * wh, "{bh:?}"); - assert!((bh.height() - bi.height()).abs() < 0.5 && bh.height() > 25.0 && bh.height() < 40.0, "{bh:?} {bi:?}"); + // The bundled font's H spans (90, 0)–(562, 656) of its 1000-unit em: at 50 pt from x = 10 that + // is 14.5 to 38.1, 32.8 tall. + assert!((bh.x0 - 14.5).abs() < 0.01 && (bh.width() - 23.6).abs() < 0.01 && (bh.height() - 32.8).abs() < 0.01, "{bh:?}"); + // In the y-down document the baseline at y = 20 lands at 80, and the cap height 32.8 above it at 47.2. + assert!((bh.y0 - 47.2).abs() < 0.01 && (bh.y1 - 80.0).abs() < 0.01, "{bh:?}"); + assert!((bh.height() - bi.height()).abs() < 0.5, "{bh:?} {bi:?}"); assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}"); } @@ -78,8 +82,12 @@ fn type42_descendants_measure_space_and_outline_their_glyphs() { check(format!("(\\000\\001\\000\\002) stringwidth pop {} sub abs 0.01 lt", 50.0 * (wh + wi))); // xyshow places each character where its numbers say. check("gsave nulldevice 10 20 moveto (\\000\\001\\000\\002) [30 0 7 0] xyshow currentpoint grestore pop 47 sub abs 0.01 lt".into()); - // charpath outlines them. - check("newpath 10 20 moveto (\\000\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into()); + // charpath outlines them: the H's box is (14.5, 20)–(38.1, 52.8). + check( + "newpath 10 20 moveto (\\000\\001) true charpath pathbbox 52.8 sub abs 0.01 lt exch 38.1 sub abs 0.01 lt and \ + exch 20 sub abs 0.01 lt and exch 14.5 sub abs 0.01 lt and" + .into(), + ); } /// A descendant that is a font by name only (its program isn't run) sets its characters as type, diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 6830fb5b41..e7fd734240 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -241,6 +241,7 @@ fn cmyk_jpegs_keep_their_ink_amounts() { /ImageMatrix [2 0 0 -2 0 2] /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{data}>" )); let got = inks(&r).data; + assert_eq!(got.len(), want.len(), "{decode}: {got:?}"); assert!(got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 3), "{decode}: {got:?}"); } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 2d8d270cc7..d4c066dd95 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2240,6 +2240,38 @@ fn ai_variable_bindings_bind_the_objects_they_name() { assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings); } +/// Hidden, locked type whose style comes in as a group of its drawn look and the type (the look has +/// its own transparency) is hidden and locked on that group. A visibility variable bound to the +/// type binds the group, so showing it shows the type; a text variable still binds the type. +#[test] +fn a_visibility_variable_on_hidden_styled_type_binds_the_group_that_hides_it() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str| { + let uid = "/XMLUIDREF : (type_x5F_1) ;"; + let attributes = [("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name)), ("docRef", XmlValue::Raw(uid))]; + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![declare("v_shown", "visibility"), declare("v_text", "textcontent")]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + // The look at half opacity; the type hidden (`1 Xw`) and locked (`1 A`), with its XML id. + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let styled = format!("{look}1 Xw\n1 A\n{own}{}1 (Unlisted) XW\n0 Xw\n0 A\n", named("type_x5F_1")); + let art = native_with_text(&(library + &layer("Art", true, &styled)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let a = d.layers[0].children().unwrap(); + let [group] = a.as_slice() else { panic!("one group of the look and the type: {a:#?} {notes:?}") }; + assert!(matches!(group.kind, NodeKind::Group { .. }) && !group.visible && group.locked, "{group:#?}"); + let type_id = group.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id); + assert!(type_id.is_some(), "{group:#?}"); + let vars = &d.variables; + assert_eq!(vars.objects_of("v_shown"), [group.id], "the hidden group, not the type in it: {notes:?}"); + assert_eq!(vars.objects_of("v_text").first().copied(), type_id, "{notes:?}"); +} + /// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its /// page with the swatches and color groups of that palette in place of the defaults. #[test] @@ -8238,6 +8270,7 @@ fn type_with_a_distort_effect_comes_in_as_type_with_it_live() { // An angle that isn't a number: the drawing as paths, and no effect on the type. let (texts, paths) = open("Adobe Twirl", "NaN /Real (angle) ,\n"); assert_eq!(paths, 1, "{texts:?}"); + assert_eq!(texts.len(), 1, "{texts:?}"); assert!(texts.iter().all(|(_, effects)| effects.is_empty()), "{texts:?}"); } @@ -8663,3 +8696,390 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() { let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0); assert!(!read, "the uncapped dimension must still match: {w:?}"); } + +/// A locked layer as the format writes it. +fn locked_layer(name: &str, body: &str) -> String { + format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n") +} + +#[test] +fn ai_locked_layers_and_groups_preserve_locks() { + let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10)); + let plain_layer = layer("Unlocked Layer", true, &square(0, 0)); + let locked_l = locked_layer("Locked Layer", &art_locked_group); + let n = native(&format!("{plain_layer}{locked_l}")); + let file = private(&n); + let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap(); + let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap(); + assert!(!unlocked.locked, "Unlocked Layer is not locked"); + assert!(locked.locked, "Locked Layer retains locked == true"); + let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true"); +} + +#[test] +fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); + let locked_l = locked_layer("Map Layer", &art_locked_group); + let n = native(&locked_l); + let file = private(&n); + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0)); + vis_layer.locked = false; + let mut vis_group = Node::group(pdf.alloc_id(), vec![]); + vis_group.name = Some("Locked Subgroup".to_string()); + vis_group.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_group)); + } + pdf.layers.push(Arc::new(vis_layer)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap(); + assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata"); + let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap(); + assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata"); +} + +#[test] +fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); + let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); + let layer_a = layer("Layer A", true, &art_locked_group); + let layer_b = layer("Layer B", true, &art_unlocked_group); + let n = native(&format!("{layer_a}{layer_b}")); + let file = private(&n); + + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0)); + let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]); + vis_grp_a.name = Some("SharedGroup".to_string()); + vis_grp_a.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_a.kind { + children.push(Arc::new(vis_grp_a)); + } + + let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1)); + let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]); + vis_grp_b.name = Some("SharedGroup".to_string()); + vis_grp_b.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_b.kind { + children.push(Arc::new(vis_grp_b)); + } + pdf.layers.push(Arc::new(vis_a)); + pdf.layers.push(Arc::new(vis_b)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + + let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap(); + let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap(); + let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + + assert!(grp_a.locked, "Layer A's SharedGroup is locked"); + assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked"); +} + +#[test] +fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]); + vis_unnamed.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + children.push(Arc::new(vis_unnamed)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let roads = visible_layers[0].children().unwrap()[0].clone(); + let unnamed = visible_layers[0].children().unwrap()[1].clone(); + assert_eq!(roads.name.as_deref(), Some("Roads")); + assert!(roads.locked, "Roads matched by unique name and preserved locked == true"); + assert!(!unnamed.locked, "unnamed child matched to unlocked private child"); +} + +#[test] +fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + // Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)] + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = false; + let mut priv_triangle = Node::group(doc.alloc_id(), vec![]); + priv_triangle.locked = true; + let mut priv_circle = Node::group(doc.alloc_id(), vec![]); + priv_circle.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_triangle)); + children.push(Arc::new(priv_circle)); + } + + // Visible children: [triangle (unnamed), circle (unnamed), Roads] + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_triangle = Node::group(doc.alloc_id(), vec![]); + vis_triangle.locked = false; + let mut vis_circle = Node::group(doc.alloc_id(), vec![]); + vis_circle.locked = false; + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_triangle)); + children.push(Arc::new(vis_circle)); + children.push(Arc::new(vis_roads)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let vis_tri = visible_layers[0].children().unwrap()[0].clone(); + let vis_circ = visible_layers[0].children().unwrap()[1].clone(); + let vis_rd = visible_layers[0].children().unwrap()[2].clone(); + + assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle"); + assert!(!vis_circ.locked, "unnamed circle remains unlocked"); + assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); +} + +/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the +/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and +/// those of what it holds stay out of it. +#[test] +fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + priv_layer.locked = true; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + } + let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock"); + assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds"); +} + +/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside, +/// and the PDF part without layers comes in on one layer named for its page: the editing copy's +/// locked layer doesn't lock that art, which nothing ties to it. +#[test] +fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() { + let art = native(&locked_layer("Map", &square(10, 10))); + let mut page = Document::new(300.0, 300.0); + std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into()); + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "the editing copy of another page size is set aside: {w:?}"); + assert_eq!(names(&d), ["Page 1"], "{w:?}"); + assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}"); +} + +#[test] +fn ai_unnamed_visible_child_does_not_pair_with_private_node() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_first = Node::group(doc.alloc_id(), vec![]); + vis_first.locked = false; + let mut vis_second = Node::group(doc.alloc_id(), vec![]); + vis_second.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_first)); + children.push(Arc::new(vis_second)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let first = visible_layers[0].children().unwrap()[0].clone(); + let second = visible_layers[0].children().unwrap()[1].clone(); + assert!(!first.locked, "first unnamed visible group is unlocked"); + assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group"); +} + +#[test] +fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + priv_1.locked = true; + let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0)); + priv_2.locked = false; + + let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0)); + + let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1"); + assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2"); +} + +#[test] +fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + let mut priv_buildings = Node::group(doc.alloc_id(), vec![]); + priv_buildings.name = Some("Buildings".to_string()); + priv_buildings.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_buildings)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]); + vis_roads1.name = Some("Roads".to_string()); + vis_roads1.locked = false; + let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]); + vis_roads2.name = Some("Roads".to_string()); + vis_roads2.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads1)); + children.push(Arc::new(vis_roads2)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let r1 = visible_layers[0].children().unwrap()[0].clone(); + let r2 = visible_layers[0].children().unwrap()[1].clone(); + assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); + assert!(!r2.locked, "second duplicate visible name remains unlocked"); +} + +/// #9176: a file with more text objects than the page's type can be matched with each, all but one +/// of them made from its text document, opens with its layers, and what is locked in it stays +/// locked. Only the one text object whose type isn't made is matched with the page's type; the made +/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure: +/// about two thousand text objects whose type the text document makes, a few it can't, and as many +/// pieces of type on the page, with locked groups.) +#[test] +fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() { + // Every text object against every piece of the page's type is past `MAX_PAIRS` (four million). + let many = 2050; + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)])); + let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10)); + let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc); + // The PDF part: the square, the made type where the text document puts it, once per text object, + // and as many small pieces of type apart from one another, which the one text object whose type + // isn't made takes. + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| { + let style = vectorcraft_doc::CharStyle { size, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style); + let id = page.alloc_id(); + let end = page.layers[0].children().map_or(0, |c| c.len()); + page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap(); + }; + for _ in 0..many { + put(&mut page, (58.5, 38.5), "Hi there", 14.0); + } + for k in 0..many { + // Down each column, so that no two pieces painted one after the other are on one line. + put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Map"], "{w:?}"); + let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}"); + assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}"); +} + +/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and +/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit +/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed. +fn word_of_two_text_objects(fourteen: f64, twenty: f64) -> crate::import::Imported { + let stories = [("20\r", 0, (twenty, 8180.0), (0.0, 0.0), 0.0), ("14\r", 0, (fourteen, 8180.0), (0.0, 0.0), 0.0)]; + let doc = text_document(&stories).replacen("/0 (Helvetica)", "/0 (SourceSans3-Regular)", 1); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let page = "0 1 0 0 setcmykcolor /SourceSans3-Regular findfont 14 scalefont setfont 20 61.5 moveto (2014) show"; + import(&eps(page, &art)).unwrap() +} + +/// The page can draw two text objects as one word: "20" and "14" set one after the other come out +/// of the page as one piece, "2014", that neither spells. The word is the last word of the one +/// joined to the first word of the one after it, so the page's type is theirs and nothing is noted +/// as left out. +#[test] +fn a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type() { + let r = word_of_two_text_objects(8161.5 + 13.916, 8161.5); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["20", "14"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// The two text objects the other way round ("14" before "20") don't make the page's "2014": its +/// word keeps the loss note. +#[test] +fn two_text_objects_the_other_way_round_arent_the_word_the_page_draws() { + let r = word_of_two_text_objects(8161.5, 8161.5 + 13.916); + assert!(r.warnings.iter().any(|w| w.contains("some of the page's type has no text object in the layers")), "{:?}", r.warnings); +} diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 3b45578deb..dc40025954 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -301,12 +301,23 @@ fn spread_gradients_are_written_with_their_stops_repeated() { fn a_spread_gradient_without_stops_is_written() { use vectorcraft_color::GradientSpread; for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]); - export(&d, &opts(&d), None, None).unwrap(); - export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap(); - crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap(); + let doc = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]) + }; + let (d, pad) = (doc(GradientSpread::Repeat), doc(GradientSpread::Pad)); + assert_eq!(page_of(&d, &opts(&d)), page_of(&pad, &opts(&pad)), "{kind:?}: EPS"); + assert_eq!( + export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap().bytes, + export_legacy_ai(&pad, &LegacyAiOptions::default()).unwrap().bytes, + "{kind:?}: legacy .ai" + ); + assert_eq!( + crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap().program, + crate::export_ai_editing(&pad, &crate::AiEditingOptions::default()).unwrap().program, + "{kind:?}: .ai editing data" + ); } } @@ -2359,15 +2370,15 @@ fn symbol_art_effects_are_written_where_they_draw() { #[test] fn level_preview_and_overprint_ids_read_back() { - for l in Level::ALL { - assert_eq!(Level::from_id(l.id()), Some(l)); - } + assert_eq!(Level::from_id("3"), Some(Level::Three)); assert_eq!(Level::from_id("LanguageLevel 2"), Some(Level::Two)); assert_eq!(Level::from_id("1"), None); - for p in Preview::ALL { - assert_eq!(Preview::from_id(p.id()), Some(p)); - } + assert_eq!(Level::from_id("23"), None); + assert_eq!(Preview::from_id(" TIFFCOLOR "), Some(Preview::TiffColor)); + assert_eq!(Preview::from_id("tiffBw"), Some(Preview::TiffBlackWhite)); + assert_eq!(Preview::from_id("tiff"), None); assert_eq!(Overprint::from_id("DISCARD"), Some(Overprint::Discard)); + assert_eq!(Overprint::from_id(""), None); } #[test] diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index c9e219cabf..f314fcdd15 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -422,15 +422,17 @@ mod tests { } /// A replaced file that had no access ACL gets none from the folder's default ACL, whose named - /// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) + /// users the old file's group bits would let in. The default ACL is set through its extended + /// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system + /// without ACLs.) #[cfg(target_os = "linux")] #[test] fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() { let d = dir("acl"); let f = d.join("doc.vectorcraft"); std::fs::write(&f, b"old").unwrap(); - let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status(); - if !set.is_ok_and(|s| s.success()) { + if !set_default_acl_for_nobody(&d) { + let _ = std::fs::remove_dir_all(&d); return; } write_atomic(&f, b"new").unwrap(); @@ -439,6 +441,31 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the + /// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry). + #[cfg(target_os = "linux")] + /// `false` when the folder's file system keeps no ACLs. + fn set_default_acl_for_nobody(d: &Path) -> bool { + const NO_ID: u32 = u32::MAX; + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); + } + match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) { + Ok(()) => {} + Err(e) if e == rustix::io::Errno::NOTSUP => return false, + Err(e) => panic!("setting the default ACL: {e}"), + } + let mut buf = vec![0u8; 4096]; + let probe = d.join("probe"); + std::fs::write(&probe, b"").unwrap(); + assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL"); + std::fs::remove_file(&probe).unwrap(); + true + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index f3ab848e81..2d23c4c3bc 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -1382,7 +1382,12 @@ mod tests { "{n}: {b:?}" ); let area = p.subpaths[0].area().abs(); - assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + if n == 2 { + // Two cubics with handles 4/3 of the half height long: each encloses 2/5 of the box. + assert!((area - 0.8 * 100.0 * 60.0).abs() < 1e-8, "{n}: {area}"); + } else { + assert!((area - PI * 50.0 * 30.0).abs() / area < 0.01, "{n}: {area}"); + } } // A box with no height leaves the path flat rather than dividing by zero. let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 5fb963b34d..b6678b813c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -314,8 +314,21 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { interp.get_from(o, &key_of(k), &Value::Object(o)) } -fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property_indexed(o, &key_of(k)) +/// The element at `k` when the object or its prototypes have one: [[HasProperty]], then [[Get]]. +/// An object of a host class with an indexer answers an array index with one call of the indexer, +/// made as `k in object` makes it, and has the element when the answer is not `undefined`. +fn element_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult> { + let key = key_of(k); + if crate::value::array_index(&key).is_some() + && let Some(f) = interp.host_indexer(o)? + { + let v = interp.host_index(&f, o, crate::Data::Number(k), true)?; + return Ok((!matches!(v, Value::Undefined)).then_some(v)); + } + if !interp.has_property_indexed(o, &key)? { + return Ok(None); + } + interp.get_from(o, &key, &Value::Object(o)).map(Some) } /// The estimated bytes a new element adds. diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 9b7ca4bfa5..1afff8a1f1 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -5,11 +5,12 @@ //! the range is much longer than the object has properties (a sparse array such as //! `new Array(4294967295)`), so a long empty range costs nothing and no index is allocated for //! it. The list of indices is made again whenever a script adds an index property to any object -//! while the method runs. Every index visited takes a unit of fuel. +//! while the method runs. An object of a host class with an indexer has every index of the range +//! visited, since its elements are not properties. Every index visited takes a unit of fuel. use super::{ - Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, get_at, has_at, length_of, method, native, new_array, object_to_string, put_at, - require_callable, to_integer, + Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, element_at, get_at, length_of, method, native, new_array, object_to_string, + put_at, require_callable, to_integer, }; use crate::heap::{Class, NativeKind, ObjId}; use crate::interp::{Abrupt, Interp, JsResult, strict_eq}; @@ -121,7 +122,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { impl Indices { fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec) -> JsResult { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; - if hi.saturating_sub(lo) > DENSE_SPAN { + // An object of a host class with an indexer holds its elements in the host, not in + // properties, so every index of the range is visited. + if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() { let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); if hi - lo > (present as u64).saturating_mul(8) { it.sparse = Some(it.gather(interp)?); @@ -206,11 +209,7 @@ impl Indices { /// The element at `k` when the object or its prototypes have one. fn element(interp: &mut Interp, o: ObjId, k: u64) -> JsResult> { - let k = k as f64; - if !has_at(interp, o, k)? { - return Ok(None); - } - get_at(interp, o, k).map(Some) + element_at(interp, o, k as f64) } /// ToObject of `this`, kept reachable while `f` runs. diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 6a6867b270..c262216c1c 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() { fn math_random_is_seeded_from_the_os_random_source() { // On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the // same on every page load: the seed must come from the OS (the browser's crypto) instead. - let src = include_str!("interp.rs"); - let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") }; - let body = &src[start..]; - let body = &body[..body.find("\n}").unwrap_or(body.len())]; - assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source"); + // The OS value is the generator's only state: realms given the same value draw the same + // numbers, and a different value draws different ones. + let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0)); + assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321)); // The OS value is the seed, made odd so it's never zero; a failed read still gives a seed. assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41); assert_eq!(crate::interp::random_seed_from(Ok(0)), 1); diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f134176bfc..28fb8c3408 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1714,6 +1714,61 @@ fn a_function_body_reads_its_own_new_target() { truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined"); } +/// Eval code that uses `super` or `new.target` where it may not is a `SyntaxError` before any of +/// it runs, so `x = 1` ahead of the forbidden form leaves `x` at 0 (ECMA-262 2015 sections +/// 18.2.1.1 and 15.1.1). +#[test] +fn eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "eval('x = 1; super.y');".to_string(), + "class C { m() { (0, eval)('x = 1; super.y'); } } new C().m();".to_string(), + "function F() { eval('x = 1; super.y'); } F();".to_string(), + "class C { m() { (function () { eval('x = 1; super.y'); })(); } } new C().m();".to_string(), + "eval('x = 1; super()');".to_string(), + "class C { constructor() { eval('x = 1; super()'); } } new C();".to_string(), + format!("{a}class B extends A {{ m() {{ eval('x = 1; super(1)'); }} }} new B(1).m();"), + format!("{a}class B extends A {{ constructor() {{ (0, eval)('x = 1; super(1)'); }} }} new B();"), + format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('x = 1; super(1)'); }})(); }} }} new B();"), + "function F() { eval('x = 1; super()'); } F();".to_string(), + "eval('x = 1; new.target');".to_string(), + "(() => eval('x = 1; new.target'))();".to_string(), + "function F() { (0, eval)('x = 1; new.target'); } new F();".to_string(), + ]; + let ran: Vec<&String> = calls + .iter() + .filter(|call| { + let src = format!("var x = 0, e; try {{ {call} }} catch (err) {{ e = err; }} x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(ran.is_empty(), "eval code ran or did not throw a SyntaxError: {ran:#?}"); +} + +/// The `Function` constructor throws the `SyntaxError` for `super` in the body or a parameter +/// itself, so it returns no function to call and `x = 1` in the body never runs (ECMA-262 2015 +/// section 19.2.1.1.1). +#[test] +fn a_function_body_with_super_is_not_made() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "class C { m() { f = Function('x = 1; super.y'); } } new C().m();".to_string(), + "class C { m() { f = Function('a = super.y', 'x = 1'); } } new C().m();".to_string(), + "f = Function('x = 1; super.y');".to_string(), + format!("{a}class B extends A {{ constructor() {{ super(1); f = Function('x = 1; super(1)'); }} }} new B();"), + "f = Function('x = 1; super()');".to_string(), + ]; + let made: Vec<&String> = calls + .iter() + .filter(|call| { + let src = + format!("var x = 0, f, e; try {{ {call} f(); }} catch (err) {{ e = err; }} f === undefined && x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(made.is_empty(), "Function made a function or did not throw a SyntaxError: {made:#?}"); +} + #[test] fn deep_class_chains_stay_within_the_limits() { let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();"; diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index df5829a41b..6c802ebec4 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -7,8 +7,10 @@ //! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the //! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two //! objects for one path are different objects. An object keeps its path in the host's platform -//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open` -//! and its line feed, in properties that are not enumerable; every name the getters give comes from +//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an +//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error` +//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed +//! in properties that are not enumerable; every name the getters give comes from //! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's //! `current`. //! @@ -47,7 +49,59 @@ impl Classes { } } -const PATH: &str = "__vcPath"; +/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in +/// the host's platform form as its value. A plain object a script made that carries the key is +/// refused. +pub const FOLDER_REF_KEY: &str = "\u{0}folderRef"; + +/// What a host gives for a `File` at `path`, in the host's platform form ([`crate::FILE_REF_KEY`]): +/// the script receives a `File` object for it. +pub fn file_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(crate::FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a +/// `Folder` object for it. +pub fn folder_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +impl Interp { + /// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form + /// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from + /// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there. + pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult { + let c = classes(self)?; + let proto = if folder { c.folder_proto } else { c.file_proto }; + let text = Value::str(path); + let fs = self.rooted(std::slice::from_ref(&text), |i| { + let p = parse_text(i, text.clone(), true)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) + })?; + instance(self, proto, fs) + } +} + +/// The path of `o` when the `File` or `Folder` class made it. +fn own_path(i: &Interp, o: ObjId) -> JsResult> { + Ok(match &i.object(o)?.class { + Class::FsEntry(s) => Some(Value::String(s.clone())), + _ => None, + }) +} + +/// Sets the path of the `File` or `Folder` `o` to `fs`, a path the host gave. +fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> { + let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) }; + i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?; + if let Some(ob) = i.heap.object_mut(o) + && let Class::FsEntry(path) = &mut ob.class + { + *path = s; + } + Ok(()) +} + const ERROR: &str = "__vcError"; const HANDLE: &str = "__vcHandle"; const RUN: &str = "__vcRun"; @@ -92,15 +146,16 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } -/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose -/// path is in its own slot. `None` for anything else, a `Folder` included. +/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype` +/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an +/// object made with `Object.create(File.prototype)` included. pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { let Some(c) = &i.files else { return Ok(None) }; if i.object(id)?.proto != Some(c.file_proto) { return Ok(None); } - Ok(match slot(i, id, PATH)? { - Value::String(s) => Some(s.to_rust_string()), + Ok(match own_path(i, id)? { + Some(Value::String(s)) => Some(s.to_rust_string()), _ => None, }) } @@ -116,7 +171,7 @@ fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> /// `Folder`. fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value)> { if let Some(o) = this.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((o, path)); } @@ -127,7 +182,7 @@ fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value /// `Folder`, or `String(x)`, which may hold URI escapes. fn path_text(i: &mut Interp, x: &Value) -> JsResult<(Value, bool)> { if let Some(o) = x.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((path, true)); } @@ -179,12 +234,12 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { + let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; - i.rooted(&[fs.clone(), line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; - let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[fs, line_feed.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?; + let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { - set_slot(i, o, PATH, fs.clone())?; set_slot(i, o, ERROR, Value::str(""))?; set_slot(i, o, HANDLE, Value::Number(-1.0))?; set_slot(i, o, RUN, Value::Number(-1.0))?; @@ -435,7 +490,7 @@ fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; Ok(Value::Bool(true)) } @@ -508,7 +563,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< if outcome(i, o, &r)? { let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; if matches!(fs, Value::String(_)) { - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; } } Ok(Value::Undefined) @@ -537,7 +592,7 @@ fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), + /// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form, + /// which only the classes' own methods set. + FsEntry(Str), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). UnitValue(Box), /// A promise (ECMA-262 11th edition, section 25.6) and its state. @@ -588,6 +591,7 @@ impl Class { Class::Ordinary | Class::ForIn(_) | Class::Host(_) + | Class::FsEntry(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) @@ -1150,7 +1154,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = PROP_BYTES * exports.bindings.len(); } - Class::String(s) => strings.add(s), + Class::String(s) | Class::FsEntry(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { strings.bytes += re.heap_bytes(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 7b1f0d2913..dea7247502 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -275,6 +275,7 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + // A `File` reads as its path ([`crate::FILE_REF_KEY`]). if r.hosted && let Some(path) = crate::file_classes::file_path(self, id)? { @@ -285,7 +286,7 @@ impl Interp { Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), - Class::Ordinary => { + Class::Ordinary | Class::FsEntry(_) => { let o = self.object(id)?; if o.props.len() > r.limits.entries { return Err(self.data_error(r, ErrorType::Range, "has too many entries")); @@ -349,7 +350,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); @@ -373,6 +374,14 @@ impl Interp { if depth > self.data_limits.depth { return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); } + // A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]). + if self.write_hosted + && let Data::Object(items) = &d + && let [(k, Data::String(path))] = items.as_slice() + && (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY) + { + return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY); + } Ok(match d { Data::Undefined => Value::Undefined, Data::Null => Value::Null, diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 7f20a30adf..cbbc5a5adb 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -21,7 +21,10 @@ //! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the //! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what //! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as -//! a third argument, and is true when it gives a value other than `undefined`. +//! a third argument, and is true when it gives a value other than `undefined`. The `Array.prototype` +//! methods that skip missing elements, such as `forEach` and `map`, read each index of such an +//! object with that one call and take its answer as the element, so an indexer called with `true` +//! gives the element itself, or `undefined` when there is none. //! //! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each //! member of its class and of the classes it descends from, apart from the members that are not @@ -105,7 +108,10 @@ pub struct HostClass { /// What `reflect` tells of the members, each under the name of one of `members`. A member /// without an entry has the type `unknown` and nothing else. pub info: Vec<(String, MemberInfo)>, - /// What `object[i]` gives for an array index `i`. + /// What `object[i]` gives for an array index `i`. Called with `true` as a third argument, it + /// gives the same element, or `undefined` when there is none. The `Array.prototype` methods that + /// skip missing elements, such as `forEach` and `map`, make that call and use its answer as the + /// element; reads without the third argument, such as those of `join`, are ordinary reads. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. pub construct: Option, @@ -365,7 +371,8 @@ impl Interp { /// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an /// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer - /// gets `true` as a third argument. + /// gets `true` as a third argument and gives the element itself, or `undefined` when there is + /// none, not a marker. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; if self.host_ref_size(id)?.is_none() { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 727d5b22f4..40a29ba77d 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -476,7 +476,7 @@ fn an_evaluator_with_site_is_told_where_it_is_called() { assert_eq!(given.len(), 2, "{given:?}"); assert_eq!(given[0].len(), 4, "{given:?}"); assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}"); - assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}"); + assert_eq!(given[0][2], Data::Number(3.0), "{given:?}"); assert_eq!(given[1], vec![Data::String("y".into())]); } @@ -615,7 +615,7 @@ fn an_error_says_where_in_the_source_it_was_raised() { r.start("var a = 1;\n throw new TypeError('no');").unwrap(); let e = finish(&mut r, 1).0.unwrap_err(); assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2)); - assert!(e.column >= 3, "{}", e.column); + assert_eq!(e.column, 3); assert_eq!(e.message, "TypeError: no"); } @@ -874,6 +874,29 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// An answer that cannot be read as a value, for a global function or a member of a host class, +/// is thrown at the call that waited, where the script catches it, and the run goes on. +#[test] +fn an_answer_that_cannot_be_read_is_thrown_at_the_waiting_call() { + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + for call in ["ask('x')", "thing.fetch()"] { + let source = format!("var m = 'none'; try {{ {call}; }} catch (e) {{ m = e.name + '|' + e.message; }} m + '|after'"); + let mut r = realm(1_000_000); + with_ask(&mut r); + with_thing(&mut r, None); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + r.start(&source).unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(nested.clone()).unwrap(); + let JsValue::String(out) = finish(&mut r, 1_000).0.unwrap() else { panic!("{call}: not a string") }; + assert!(out.starts_with("RangeError|") && out.contains("nested too deep") && out.ends_with("|after"), "{call}: {out}"); + } +} + /// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by /// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing` /// with the handle `[0]`. @@ -966,6 +989,26 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn an_unavailable_member_hides_the_member_its_parent_class_has() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: vec![("size".to_string(), member)], + info: Vec::new(), + index: None, + construct: None, + }; + let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))]; + let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))]; + r.define_host_classes(classes, objects).unwrap(); + r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); +} + #[test] fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() { let mut r = realm(1_000_000); @@ -1015,6 +1058,49 @@ fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() { assert_eq!(calls.get(), 1); } +/// A realm with `it`, a host collection of `len` numbers whose element `i` is `i`, and the count +/// of the indexer's calls. +fn numbers(len: usize) -> (Realm, Rc>) { + let mut r = realm(10_000_000); + let calls: Rc> = Rc::default(); + let seen = calls.clone(); + let index: HostFunction = Rc::new(move |a| { + seen.set(seen.get() + 1); + match a.get(1) { + Some(Data::Number(n)) if *n < len as f64 => Ok(Data::Number(*n)), + _ => Ok(Data::Undefined), + } + }); + let length: HostFunction = Rc::new(move |_| Ok(Data::Number(len as f64))); + let class = HostClass { + name: "Numbers".into(), + parent: None, + members: vec![("length".into(), HostMember::Get(length))], + info: Vec::new(), + index: Some(index), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Numbers", &[1.0]))]).unwrap(); + (r, calls) +} + +#[test] +fn array_methods_visit_every_element_of_a_long_host_collection() { + let (mut r, _) = numbers(5000); + let source = "var n = 0; Array.prototype.forEach.call(it, function () { n++; }); \ + var m = Array.prototype.map.call(it, function (x) { return x; }); \ + [n, m.length, m[4999], Array.prototype.lastIndexOf.call(it, 0), Array.prototype.indexOf.call(it, 4999)].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("5000,5000,4999,0,4999".into())); +} + +#[test] +fn array_methods_call_the_indexer_once_for_each_element() { + let (mut r, calls) = numbers(3); + let source = "var s = 0; Array.prototype.forEach.call(it, function (x) { s += x; }); s"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(3.0)); + assert_eq!(calls.get(), 3); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index fa4b649e74..dac4a0c729 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -254,8 +254,10 @@ pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult /// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; -/// What a [`Pause`] does with its kept values when its host call fails. -pub(crate) type FailFn = fn(&mut Interp, &[Value]); +/// What a [`Pause`] does with its kept values when its host call fails. An error it gives that is +/// not thrown (a stop, such as a host's Abort) ends the run in place of a thrown failure; a thrown +/// one gives way to the failure. +pub(crate) type FailFn = fn(&mut Interp, &[Value]) -> JsResult<()>; /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits @@ -274,6 +276,23 @@ pub(crate) struct Pause { pub(crate) struct Resumption { resume: ResumeFn, keep: Vec, + /// Runs when the answer cannot be read, so the resume function never gets it. + failed: Option, +} + +impl Resumption { + /// The built-in does not get the host's answer: its failure function runs with its kept + /// values, which `thrown` is kept from collection with. → the stop the failure function + /// gave, which ends the run in place of `thrown`. + pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) -> JsResult<()> { + let Some(failed) = self.failed else { return Ok(()) }; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(self.keep.iter().cloned()); + interp.temp_roots.push(thrown.clone()); + let r = failed(interp, &self.keep); + interp.temp_roots.truncate(mark); + r + } } pub(crate) struct Interp { @@ -378,6 +397,10 @@ pub(crate) struct Interp { /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its /// answer is read as such a member's result is ([`Interp::write_hosted`]). pub(crate) waiting_hosted: bool, + /// The answer to the call that waited could not be read as a value + /// ([`crate::Realm::answer`]): the value on top of the stack is the exception, which the next + /// step throws at that call. + pub(crate) answer_throws: bool, /// A host class's constructor runs with `new`: it may not wait for its result. pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before @@ -521,7 +544,29 @@ fn index_names_bytes(len: usize, per_entry: usize) -> usize { /// random source (the browser's crypto on the web), or the standard library's randomly keyed /// hasher when that fails; never zero. fn random_seed() -> u64 { - random_seed_from(getrandom::u64()) + random_seed_from(os_random()) +} + +#[cfg(test)] +thread_local! { + /// What the OS random source returns to realms made on this thread, when set. + pub(crate) static TEST_OS_RANDOM: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The OS random source (in tests, what `TEST_OS_RANDOM` holds when set). +fn os_random() -> Result { + test_os_random().unwrap_or_else(getrandom::u64) +} + +/// What a test set in `TEST_OS_RANDOM`. +#[cfg(test)] +fn test_os_random() -> Option> { + TEST_OS_RANDOM.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_os_random() -> Option> { + None } /// [`random_seed`] from what the OS random source returned. @@ -690,6 +735,7 @@ impl Interp { can_wait: Rc::default(), waiting: false, waiting_hosted: false, + answer_throws: false, constructing: false, resuming: None, again: None, @@ -1031,6 +1077,11 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // An answer that could not be read is thrown at the call that waited for it. + if std::mem::take(&mut self.answer_throws) { + let thrown = self.pop()?; + return Err(Abrupt::Throw(thrown)); + } // A built-in that waited for the host takes the answer on top of the stack before the // instruction after its call runs; what it throws is thrown at that call. if let Some(r) = self.resuming.take() { @@ -3560,6 +3611,7 @@ impl Interp { Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; + let mut stop = Ok(()); if let Err(e) = &answer && let Some(failed) = failed { @@ -3567,11 +3619,15 @@ impl Interp { if let Abrupt::Throw(v) = e { self.temp_roots.push(v.clone()); } - failed(self, &keep); + stop = failed(self, &keep); } self.temp_roots.truncate(mark); + // A stop from `failed` is not masked by a thrown error the script could catch. + if matches!(answer, Err(Abrupt::Throw(_))) { + stop?; + } let answer = answer?; - let r = Resumption { resume, keep }; + let r = Resumption { resume, keep, failed }; if self.waiting && !was_waiting { self.resuming = Some(r); return Ok(answer); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 8bab95b715..bbf2b0a962 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -168,6 +168,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; +pub use file_classes::{FOLDER_REF_KEY, file_ref, folder_ref}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 51b1e990f1..1fbdb5c003 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -369,7 +369,7 @@ fn combinator_rejection_relays_keep_the_input_location() { let reported = r.unhandled_rejections(); assert_eq!(reported.len(), 1, "{method}: {reported:?}"); assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); - assert!(reported[0].column > 0); + assert_eq!(reported[0].column, 3, "{method}: {:?}", reported[0]); assert_eq!(reported[0].tag, r.script_tag()); } let mut r = realm(); @@ -377,7 +377,7 @@ fn combinator_rejection_relays_keep_the_input_location() { .unwrap(); assert_eq!(r.unhandled_rejections().len(), 1); assert_eq!(r.unhandled_rejections()[0].line, 3); - assert!(r.unhandled_rejections()[0].column > 0); + assert_eq!(r.unhandled_rejections()[0].column, 3); let mut r = realm(); r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); let reported = r.unhandled_rejections(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 439b231d16..822477780f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -209,6 +209,17 @@ impl Realm { Self::with_options(Options::default(), Limits::default()) } + /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source + /// had returned it. The realm is made by [`Realm::new`], so its seed comes through the same + /// path as any other realm's. + #[cfg(test)] + pub(crate) fn with_os_random(os: Result) -> Self { + crate::interp::TEST_OS_RANDOM.with(|c| c.set(Some(os))); + let realm = Self::new(); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(None)); + realm + } + /// A realm whose scripts (and the source given to `eval` and `Function`) are read with /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. @@ -380,6 +391,7 @@ impl Realm { interp.host_abort = None; interp.waiting = false; interp.waiting_hosted = false; + interp.answer_throws = false; interp.constructing = false; interp.resuming = None; interp.again = None; @@ -426,6 +438,7 @@ impl Realm { interp.join_stack.clear(); interp.waiting = false; interp.waiting_hosted = false; + interp.answer_throws = false; interp.constructing = false; interp.resuming = None; interp.again = None; @@ -566,8 +579,10 @@ impl Realm { /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown - /// at its call. A result past the heap limit ends the run with that - /// limit, and with no call waiting this gives an internal error. + /// at its call. A result that cannot be read as a value, such as one nested too deep, is + /// thrown at the call as an immediate result would be, and the built-in does not get it. A + /// result past the heap limit ends the run with that limit, and with no call waiting this gives + /// an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; if !interp.waiting { @@ -584,10 +599,28 @@ impl Realm { let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; - let r = written.and_then(|v| { - interp.stack.pop(); - interp.push(v) - }); + let r = match written { + // An answer that cannot be read as a value (too deep, too many entries, a stale host + // reference) is thrown at the call, where the script can catch it, and a built-in + // that waited with the call does not get it: it fails as when its host call throws. A + // stop its failure gives (an Abort from the host) ends the run before the error is + // thrown. + Err(Abrupt::Throw(thrown)) => { + interp.stack.pop(); + let stop = match interp.resuming.take() { + Some(r) => r.fail(interp, &thrown), + None => Ok(()), + }; + stop.and_then(|()| { + interp.answer_throws = true; + interp.push(thrown) + }) + } + written => written.and_then(|v| { + interp.stack.pop(); + interp.push(v) + }), + }; match r { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 47d8aeaffb..a5f74e7f54 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1543,16 +1543,21 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { }) } -/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. -fn failed(i: &mut Interp, keep: &[Value]) { - let Some(win) = arg(keep, 0).as_object() else { return }; +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. → a stop +/// (an Abort) the host's `end` gave; an error `end` throws gives way to the failure. +fn failed(i: &mut Interp, keep: &[Value]) -> JsResult<()> { + let Some(win) = arg(keep, 0).as_object() else { return Ok(()) }; if classes(i).ok().and_then(|c| c.showing) != Some(win) { - return; + return Ok(()); } set_showing(i, None); if let Ok(end) = host_fn(i, "end") { - let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + match i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]) { + Ok(_) | Err(Abrupt::Throw(_)) => {} + Err(stop) => return Err(stop), + } } + Ok(()) } /// `show()` ends with `result`. @@ -1611,10 +1616,15 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu Abrupt::Throw(t) => vec![t.clone()], _ => Vec::new(), }; + let thrown_error = !thrown.is_empty(); let mark = i.temp_roots.len(); i.temp_roots.extend(thrown); - failed(i, keep); + let stop = failed(i, keep); i.temp_roots.truncate(mark); + // A stop from `end` is not masked by a thrown error the script could catch. + if thrown_error { + stop?; + } } v } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index dc4a942d6c..dafe4dabc8 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -229,6 +229,82 @@ fn a_dialog_can_be_shown_again_after_it_closed() { assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); } +/// An event the host gives a waiting `show()` that cannot be read is thrown at `show()`, and the +/// dialog is no longer showing, so it can be shown again. +#[test] +fn an_event_that_cannot_be_read_ends_show_and_the_dialog_can_show_again() { + let (mut r, seen, _) = realm(Vec::new()); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + r.start("var w = new Window('dialog'), m = 'none'; try { w.show(); } catch (e) { m = e.name; } m + '|' + w.show()").unwrap(); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(nested).unwrap(); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits(), "the second show waits for its event"); + r.answer(close()).unwrap(); + let mut out = r.advance(100_000).unwrap(); + while out == Progress::Paused { + out = r.advance(100_000).unwrap(); + } + assert_eq!(out, Progress::Done(JsValue::String("RangeError|0".into()))); + assert_eq!(seen.borrow().ends, vec![(0.0, false), (0.0, true)]); +} + +/// A realm whose `end` stops the run (an Abort) when `show()` ends without its result, whose +/// `open` throws when `open_fails`, and whose `wait` gives `events` in order, then waits. +fn stopping_realm(open_fails: bool, events: Vec) -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let queue = RefCell::new(VecDeque::from(events)); + let open: HostFunction = Rc::new(move |_| if open_fails { Err(HostError::Error("no window".into())) } else { Ok(Data::Undefined) }); + let wait: HostFunction = Rc::new(move |_| queue.borrow_mut().pop_front().ok_or(HostError::Wait)); + let end: HostFunction = Rc::new(|args| match args.get(1) { + Some(Data::Bool(true)) => Ok(Data::Undefined), + _ => Err(HostError::Abort("stopped by the host".into())), + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + r +} + +fn is_host_stop(e: &RunError) -> bool { + e.kind == RunErrorKind::Limit(LimitKind::Host) && e.message == "stopped by the host" +} + +/// A stop the host's `end` gives when `show()` fails ends the run: the script cannot catch the +/// failure and go on, whether the event could not be read, the host call threw or a handler threw. +#[test] +fn a_stop_from_end_when_show_fails_ends_the_run() { + let caught = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + b.onClick = function () { throw new Error('handler'); }; \ + try { w.show(); } catch (e) {} 'went on'"; + + let mut r = stopping_realm(false, Vec::new()); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + r.start(caught).unwrap(); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits()); + let answered = r.answer(nested); + assert!(answered.as_ref().is_err_and(is_host_stop), "unreadable event: {answered:?}"); + + let mut r = stopping_realm(true, Vec::new()); + let ran = r.run(caught); + assert!(ran.as_ref().is_err_and(is_host_stop), "open threw: {ran:?}"); + + let mut r = stopping_realm(false, vec![click(1)]); + let ran = r.run(caught); + assert!(ran.as_ref().is_err_and(is_host_stop), "handler threw: {ran:?}"); +} + #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 5aee375abd..d1fdb6aefc 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -113,7 +113,7 @@ fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() { fn packet_padding_requires_an_actual_wrapper_trailer() { let packet = r#""#; assert_eq!(xmp::pad_size(packet), 0); - assert!(xmp::pad_size(PACKET) > 0); + assert_eq!(xmp::pad_size(PACKET), 1); let prefixed = format!("\n\n{PACKET}"); assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET)); assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); diff --git a/crates/js/tests/json2.rs b/crates/js/tests/json2.rs index af408a4fef..521040373e 100644 --- a/crates/js/tests/json2.rs +++ b/crates/js/tests/json2.rs @@ -68,20 +68,16 @@ problem; #[test] fn json2_polyfill_round_trips_with_the_built_in_json() { + let mut realm = Realm::new(); + match realm.run(NEEDS) { + Ok(JsValue::Bool(true)) => {} + other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"), + } let Some(path) = json2_file() else { println!("json2: SKIPPED (no json2.js; run cargo xtask test262)"); return; }; let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let mut realm = Realm::new(); - match realm.run(NEEDS) { - Ok(JsValue::Bool(true)) => {} - Ok(JsValue::Bool(false)) => { - println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)"); - return; - } - other => panic!("json2: the built-in check failed: {other:?}"), - } match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) { Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"), other => panic!("json2: {other:?}"), diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 8aa221b4a6..b5544b958c 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -33,3 +33,7 @@ craft-image-codecs = { workspace = true } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } socket2 = { workspace = true } + +# The files of other crates that this crate's tests compile, for CI's test selection. +[package.metadata.craft] +reads = ["crates/apischema/src/conformance.rs"] diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d9bf1c8d98..98267484e0 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -514,7 +514,7 @@ pub fn tool_definitions() -> Vec { tool( "text_wrap", "Text wrap", - "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", + "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). A type object in `ids` below another of them is the text to wrap, not a wrap object. A `warning` says when no area type lies below them. `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..6852f317b3 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -735,6 +735,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", ), + ( + "tool.quickPen.arcLarger", + "Increase Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° larger, for the last sharp-corner arc of the path being drawn and the arcs after it, as ] and Ctrl+wheel up over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size above 359°", + ), + ( + "tool.quickPen.arcSmaller", + "Decrease Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° smaller, for the last sharp-corner arc of the path being drawn and the arcs after it, as [ and Ctrl+wheel down over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size below 1°", + ), ( "window.dock", "Panels", @@ -1192,7 +1204,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1274,7 +1286,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. 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", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.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", @@ -1292,7 +1304,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1310,13 +1322,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1531,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1549,19 +1561,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", "More Options", "", - "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + "{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", ), ( "ui.dialogReset", @@ -1645,7 +1657,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1663,7 +1675,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1918,7 +1930,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.reset", "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( "ui.actionSet.clear", @@ -1949,7 +1961,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", @@ -2202,7 +2214,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 15eca240a9..42a66bc8d5 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -731,7 +731,8 @@ fn hatched_brushes_fill_with_their_average_color() { let p = paths(&back.document); assert_eq!(p.len(), 1); let [r, g, b] = fill_rgb(&p[0]).unwrap(); - assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]); + // The horizontal hatch covers one row in eight of its 8 × 8 tile: 8 blue and 56 white pixels. + assert_eq!([r, g, b], [223, 223, 255]); // With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill. let mut records = records; records.insert(0, (18, le(&[1]))); @@ -739,7 +740,8 @@ fn hatched_brushes_fill_with_their_average_color() { let p = paths(&back.document); assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255])); let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; - assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity); + // One eighth of 255, truncated to 31. + assert!((f.opacity - 31.0 / 255.0).abs() < 1e-6, "{}", f.opacity); } #[test] diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 2397045a84..f41873333c 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option; Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on. -`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region. ```rust pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index 2b2fd9512e..f1eaa29283 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -816,11 +816,14 @@ mod tests { // Squaring these lengths overflows f64. let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); let sp = smooth_bridge(a, b, 5e153).unwrap(); + // At least one anchor for each of the two circles and the two arcs. + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); assert_smooth(&sp); // The two radius sums fit in f64, but not their total. let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); // The arcs' centers would lie beyond the largest f64. let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); diff --git a/crates/pathops/src/addons/pathtools/shapes.rs b/crates/pathops/src/addons/pathtools/shapes.rs index e0ecc241be..dc61429c34 100644 --- a/crates/pathops/src/addons/pathtools/shapes.rs +++ b/crates/pathops/src/addons/pathtools/shapes.rs @@ -609,12 +609,12 @@ mod tests { fn each_kind_draws_a_closed_outline_in_its_box() { for kind in ShapeKind::ALL { let s = shape(kind); - assert_eq!(ShapeKind::parse(kind.id()), Some(kind)); assert_eq!(s.check(), Ok(()), "{kind:?}"); let p = s.path().unwrap(); assert!(closed(&p) && within_box(&p, &s), "{kind:?}: {:?}", p.bounds()); assert!(p.anchors().all(|(_, _, a)| a.p.x.is_finite() && a.p.y.is_finite())); } + assert_eq!(ShapeKind::parse("gear"), Some(ShapeKind::Gear)); assert_eq!(ShapeKind::parse("cloud"), None); } diff --git a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs index 38e7c49e3b..ef84d72f83 100644 --- a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs +++ b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs @@ -262,9 +262,7 @@ fn a_smooth_end_whose_handles_part_turns_into_a_corner() { } #[test] -fn follow_names_round_trip() { - for f in Follow::ALL { - assert_eq!(Follow::parse(f.id()), Some(f)); - } +fn follow_names_parse() { + assert_eq!(Follow::parse("b"), Some(Follow::Second)); assert_eq!(Follow::parse("up"), None); } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d02e5a8a93..da7960af0f 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -31,10 +31,12 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, + try_pathfinder_with, }; pub use planar::{ - Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, - encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, + TooManyPieces, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, + shape_builder, shape_builder_with_gap, try_live_paint, try_live_paint_with_gaps, }; pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 102d7e7138..8389fd2dbb 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -109,6 +109,36 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec { pathfinder_with(op, shapes, DEFAULT_PRECISION) } +/// [`pathfinder_with`], or [`TooManyPieces`](crate::TooManyPieces) when Divide's open paths and the +/// shapes they cut have more than [`SHAPE_BUILDER_MAX_SEGMENTS`](crate::SHAPE_BUILDER_MAX_SEGMENTS) +/// segments, or the sweep cuts them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`](crate::SHAPE_BUILDER_MAX_MAP_EDGES) pieces, or they exceed the +/// sweep's work budget. [`pathfinder_with`] then divides only the filled areas and leaves the open +/// paths out. +pub fn try_pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Result, crate::TooManyPieces> { + if op == PathfinderOp::Divide && crate::has_open_path(shapes) { + let precision = if precision.is_finite() && precision > 0.0 { precision } else { DEFAULT_PRECISION }; + let (faces, capped) = divide_with_open_paths(shapes, precision, false); + return if capped { Err(crate::TooManyPieces) } else { Ok(faces) }; + } + Ok(pathfinder_with(op, shapes, precision)) +} + +/// Divide with open paths as cutting edges, through the Shape Builder's bounded planar map (and, +/// with `fallback`, its filled-area fallback), and whether that map was skipped for its size. +fn divide_with_open_paths(shapes: &[Shape], precision: f64, fallback: bool) -> (Vec, bool) { + let (arrangement, capped) = crate::planar::builder_capped(shapes, false, 0.0, precision, fallback); + let faces = arrangement + .regions + .into_iter() + .filter_map(|r| { + let key = shapes.get(r.top()?)?.key; + Some(Shape::new(r.path, FillRule::NonZero, key)) + }) + .collect(); + (faces, capped) +} + /// [`pathfinder`] at Pathfinder Options › Precision: results are refit to within `precision` /// (document units) and pieces thinner than it are dropped. A smaller value follows the inputs more /// closely. A value that isn't positive and finite is [`DEFAULT_PRECISION`]. @@ -130,14 +160,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve // Open paths are cutting edges for Divide; the filled-only operations keep their // implicit closure. Reuse Shape Builder's bounded planar map and its fallback. if op == PathfinderOp::Divide && crate::has_open_path(shapes) { - return crate::planar::builder(shapes, false, 0.0, precision) - .regions - .into_iter() - .filter_map(|r| { - let key = shapes.get(r.top()?)?.key; - Some(Shape::new(r.path, FillRule::NonZero, key)) - }) - .collect(); + return divide_with_open_paths(shapes, precision, true).0; } let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; let p = &arr.tidy; @@ -561,6 +584,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec { arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default() } +/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces +/// (the faces are then not built). +pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option> { + let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) }; + if a.top.segment_indices().nth(max_edges).is_some() { + return None; + } + Some(regions_of(&a)) +} + /// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon /// as the face past `limit` is built (the faces after it are not built). pub fn regions_within(shapes: &[Shape], limit: usize) -> Option> { @@ -1635,6 +1668,8 @@ mod tests { assert_eq!(faces.len(), 1, "a segment past the cap falls back to filled areas"); assert_eq!(faces[0].key, 7); assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6); + // The checked Divide reports that it left the lines out. + assert_eq!(try_pathfinder_with(PathfinderOp::Divide, &inputs, DEFAULT_PRECISION), Err(crate::TooManyPieces)); } fn old_trim(shapes: &[Shape], precision: f64) -> Vec { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index f702f993ed..2d1eee08c9 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -37,14 +37,14 @@ pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; -pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; +pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps, try_live_paint, try_live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder, - shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, TooManyPieces, cut_out, encloses_area, + has_open_path, run_around, shape_builder, shape_builder_with_gap, }; -pub(crate) use shape_builder::{builder, gap_inputs}; +pub(crate) use shape_builder::{builder_capped, gap_inputs}; #[cfg(test)] mod tests; diff --git a/crates/pathops/src/planar/live_paint.rs b/crates/pathops/src/planar/live_paint.rs index 1b9d5b6177..a98449dd0a 100644 --- a/crates/pathops/src/planar/live_paint.rs +++ b/crates/pathops/src/planar/live_paint.rs @@ -6,26 +6,72 @@ use super::*; /// Faces are the bounded areas the paths enclose, holes included, each with the inputs whose fill /// covers it (ascending; empty for an area only enclosed by paths). Edges are the paths split /// wherever they meet another path, keyed by the input they came from (the front-most where -/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate). +/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate), or when +/// the sweep cuts them into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed +/// the sweep's work budget ([`try_live_paint`] reports either limit). pub fn live_paint(shapes: &[Shape]) -> (Vec, Vec) { - build(shapes, DEFAULT_PRECISION).map(|(faces, edges, _)| (faces, edges)).unwrap_or_default() + try_live_paint(shapes).unwrap_or_default() } +/// [`live_paint`], or [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +/// No faces or edges are built in either case. +pub fn try_live_paint(shapes: &[Shape]) -> Result<(Vec, Vec), TooManyPieces> { + Ok(build(shapes, DEFAULT_PRECISION)?.map(|(faces, edges, _)| (faces, edges)).unwrap_or_default()) +} + +/// Faces, edges and gaps, as [`live_paint_with_gaps`] gives them. +type WithGaps = (Vec, Vec, Vec<[Point; 2]>); + +type Capped = Result; + +type CappedWithGaps = (Capped>, Capped>, Vec<[Point; 2]>); + /// [`live_paint`] with Gap Detection: the faces are those of `shapes` with a line across each gap /// [`find_gaps`] finds up to `max_gap`, so paint stops at the gaps, and the edges are those of /// `shapes` alone (the lines add none). Also returns the gaps. pub fn live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> (Vec, Vec, Vec<[Point; 2]>) { + let (faces, edges, gaps) = faces_and_edges_with_gaps(shapes, max_gap); + (faces.unwrap_or_default(), edges.unwrap_or_default(), gaps) +} + +/// [`live_paint_with_gaps`], or [`TooManyPieces`] when the sweep cuts the paths, or the paths with +/// the lines across their gaps, into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or either +/// set of paths exceeds the sweep's work budget. +pub fn try_live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> Result { let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + let (faces, edges) = try_live_paint(shapes)?; + return Ok((faces, edges, gaps)); + }; + let (faces, _) = try_live_paint(&closed)?; + let (_, edges) = try_live_paint(shapes)?; + Ok((faces, edges, gaps)) +} + +/// The faces and the edges of [`live_paint_with_gaps`], each built on its own, and the gaps. +fn faces_and_edges_with_gaps(shapes: &[Shape], max_gap: f64) -> CappedWithGaps { + let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + return match try_live_paint(shapes) { + Ok((faces, edges)) => (Ok(faces), Ok(edges), gaps), + Err(e) => (Err(e), Err(e), gaps), + }; + }; + let faces = try_live_paint(&closed).map(|(faces, _)| faces); + let edges = try_live_paint(shapes).map(|(_, edges)| edges); + (faces, edges, gaps) +} + +/// `shapes` with a line across each of `gaps`, or `None` when there are none. +fn with_gap_lines(shapes: &[Shape], gaps: &[[Point; 2]]) -> Option> { if gaps.is_empty() { - let (faces, edges) = live_paint(shapes); - return (faces, edges, gaps); + return None; } let mut closed = shapes.to_vec(); let lines = PathData::new(gaps.iter().map(|g| SubPath::polyline(g, false)).collect()); closed.push(Shape::new(lines, FillRule::NonZero, u64::MAX)); - let (faces, _) = live_paint(&closed); - let (_, edges) = live_paint(shapes); - (faces, edges, gaps) + Some(closed) } /// How many times longer than a gap the way between its two ends along the paths must be for it to diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index f2c4b200d3..f2114a6ceb 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,6 +42,18 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { + map_within(shapes, cover, precision, usize::MAX).ok().flatten() +} + +/// [`map_with`], or [`TooManyPieces`] when the sweep cuts the paths into more than `max_edges` pieces +/// or the inputs exceed the sweep's work budget. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Result, TooManyPieces> { + let mut capped = false; + let map = map_capped(shapes, cover, precision, max_edges, &mut capped); + if capped { Err(TooManyPieces) } else { Ok(map) } +} + +fn map_capped(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize, capped: &mut bool) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -66,10 +78,11 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< snap_horizontals(&mut inputs.iter_mut().map(|p| &mut p.0).collect::>(), eps); // Counted on the snapped geometry, which is what the sweep sees: snapping can bring boxes into contact. if !crate::budget::sweep_fits(inputs.iter().map(|p| &p.0)) { + *capped = true; return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges, capped)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -188,11 +201,18 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec, Vec)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize, capped: &mut bool) -> Option<(Vec, Vec)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); let top = sweep.ok()?.ok()?; + // What is built from here on takes time and memory in proportion to the pieces the sweep cut + // the paths into, and paths that cross many times are cut into far more pieces than they have + // segments. + if top.segment_indices().nth(max_edges).is_some() { + *capped = true; + return None; + } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than // the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge // a rounding error away from where it cuts that edge). @@ -426,9 +446,17 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. -pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { - let m = map_with(shapes, false, precision)?; - let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; +/// This returns [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +pub(super) fn build(shapes: &[Shape], precision: f64) -> Result, TooManyPieces> { + Ok(map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?.and_then(|m| build_from(&m, shapes, precision))) +} + +/// Faces, edges and the open paths' pieces under another path, as [`build`] gives them. +pub(super) type Built = (Vec, Vec, Vec); + +fn build_from(m: &Map, shapes: &[Shape], precision: f64) -> Option { + let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = m; let snap = *snap; let fills: Vec = shapes.iter().map(Fill::new).collect(); let subpath = |cycle: &[usize]| { diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index fcfb6cea95..86a2fc5f36 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -9,6 +9,30 @@ use super::*; /// can take on art far past what a drawing holds. pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; +/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and +/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open +/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces +/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make +/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory. +/// Past this the Shape Builder skips the full map and keeps only the regions of the filled areas, +/// which are capped on their own: when the open paths alone cross too often, a filled shape apart +/// from them still has its region. +pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; + +/// The paths have more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments, or the sweep cut them into +/// more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or they exceed the sweep's work budget. +/// Their planar map was not built. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TooManyPieces; + +impl std::fmt::Display for TooManyPieces { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the paths have too many segments or pieces") + } +} + +impl std::error::Error for TooManyPieces {} + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -40,7 +64,10 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// nothing fills, and each path with no closed subpath comes back cut wherever another path meets /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas -/// count and there are no pieces. +/// count and there are no pieces. The same happens when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They +/// then have no regions when they alone are cut into more pieces than that, and a filled area +/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions). pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } @@ -73,23 +100,43 @@ pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> Builde /// [`shape_builder_with_gap`] refitting its results to `precision` (Pathfinder Options › Precision). pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -> BuilderArrangement { + builder_capped(shapes, edges, gap, precision, true).0 +} + +/// [`builder`], and whether its full map was skipped because the paths have more than +/// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or the sweep cut them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or the inputs exceed the sweep's work budget. +/// The regions are then the filled areas', or, without `fallback`, there are none and the filled +/// areas are not swept. +pub(crate) fn builder_capped(shapes: &[Shape], edges: bool, gap: f64, precision: f64, fallback: bool) -> (BuilderArrangement, bool) { let has_open = has_open_path(shapes); let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); + let mut capped = segments > SHAPE_BUILDER_MAX_SEGMENTS; + let mut built = |shapes: &[Shape]| match build(shapes, precision) { + Ok(b) => b.unwrap_or_default(), + Err(TooManyPieces) => { + capped = true; + Default::default() + } + }; let planar = (segments <= SHAPE_BUILDER_MAX_SEGMENTS) .then(|| { let keyed: Vec = shapes.iter().enumerate().map(|(i, s)| Shape::new(s.path.clone(), s.rule, i as u64)).collect(); if has_open && gap.is_finite() && gap > 0.0 { - let (faces, pieces, under) = build(&gap_inputs(&keyed, gap), precision).unwrap_or_default(); + let (faces, pieces, under) = built(&gap_inputs(&keyed, gap)); // Gap targets split original outlines too, but the bridges themselves aren't art. let art = |p: &Shape| p.key < shapes.len() as u64; (faces, pieces.into_iter().filter(art).collect(), under.into_iter().filter(art).collect()) } else { - build(&keyed, precision).unwrap_or_default() + built(&keyed) } }) .filter(|(faces, pieces, _)| !faces.is_empty() || !pieces.is_empty()); let Some((faces, pieces, under)) = planar else { - return BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }; + if capped && !fallback { + return (BuilderArrangement::default(), true); + } + return (BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }, capped); }; let is_line = |i: u64| shapes.get(i as usize).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); let (lines, outline): (Vec, Vec) = pieces.into_iter().partition(|e| is_line(e.key)); @@ -97,29 +144,32 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - faces } else { // The filled areas from their arrangement, whose faces merge exactly, then the gaps. - let mut regions = crate::pathfinder::regions_with(shapes, precision); + let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; - BuilderArrangement { + let arrangement = BuilderArrangement { regions, lines: if has_open { lines } else { Vec::new() }, edges: if edges { outline } else { Vec::new() }, lines_under: if has_open { under } else { Vec::new() }, - } + }; + (arrangement, false) } /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no /// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its /// size budget and take the filled shapes down with it; the regions keep the original indices. +/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. fn filled_regions(shapes: &[Shape], precision: f64) -> Vec { let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp)); let keep: Vec = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect(); if keep.len() == shapes.len() { - return crate::pathfinder::regions_with(shapes, precision); + return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); } let kept: Vec = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect(); - crate::pathfinder::regions_with(&kept, precision) + crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES) + .unwrap_or_default() .into_iter() .map(|mut r| { r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect(); diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index ad888448a7..99045828f6 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -603,6 +603,75 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() { assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty())); } +/// `n` horizontal and `n` vertical lines across one square, every one crossing every other. +fn line_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64)); + let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64)); + across.chain(down).collect() +} + +/// `n` horizontal and `n` vertical bars across one square, every one crossing every other. +fn bar_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64)); + let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64)); + across.chain(down).collect() +} + +#[test] +fn a_map_past_its_edge_cap_is_not_built() { + // 20 lines each way: each line is cut into 21 pieces, 840 in all. + let s = line_grid(20); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_ok_and(|m| m.is_some())); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_err()); + let bars = bar_grid(20); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); +} + +#[test] +fn divide_and_live_paint_report_the_edge_cap() { + // A filled square under 300 lines each way: the lines cross past the cap. + let mut s = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + s.extend(line_grid(300).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION), Err(TooManyPieces)); + // Without the report, Divide gives back the square alone, uncut. + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&s), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&s, 10.0), Err(TooManyPieces)); + // Overlapping lines exceed the sweep's work budget before any pieces are cut. + let mut overlapping = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + overlapping.extend((0..1500).map(|i| line((0.0, 0.0), (1000.0, 1000.0), i + 8))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION), Err(TooManyPieces)); + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&overlapping), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&overlapping, 10.0), Err(TooManyPieces)); + let (faces, edges) = live_paint(&overlapping); + assert!(faces.is_empty() && edges.is_empty()); + // Under the cap, both build as before. + let mut small = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + small.extend(line_grid(20).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &small, DEFAULT_PRECISION).is_ok_and(|f| f.len() > 1)); + assert!(try_live_paint(&small).is_ok_and(|(faces, _)| faces.len() > 1)); +} + +#[test] +fn shape_builder_builds_no_regions_past_its_edge_cap() { + // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about + // 180,000 pieces, past the cap, and nothing is built from them. + let s = line_grid(300); + let started = work_done(); + let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true); + assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len()); + assert_eq!(work_done() - started, 0, "no face or edge was looked up"); + // Bars, closed paths only, each edge crossing 300 others: their filled areas are not built + // either. + assert!(shape_builder(&bar_grid(150), true).regions.is_empty()); + // Under the cap, the same grid is built. + assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19); +} + #[test] fn shape_builder_stays_quick_up_to_its_cap() { // A wavy ring of nearly the most segments the map takes, crossed by a few lines. diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index e26d0e69e9..504d8af795 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -738,6 +738,8 @@ fn simplify_levels_and_auto_simplify() { #[test] fn smooth_rounds_corners() { let s = smooth(&rect(0.0, 0.0, 10.0, 10.0), 1.0); + // The four corners stay, each made smooth. + assert_eq!(s.anchor_count(), 4, "{s:?}"); assert!(s.anchors().all(|(_, _, a)| a.has_in() && a.has_out())); let same = smooth(&rect(0.0, 0.0, 10.0, 10.0), 0.0); assert_eq!(same, rect(0.0, 0.0, 10.0, 10.0)); @@ -959,7 +961,7 @@ fn grid_split() { } #[test] -#[ignore] +#[ignore = "benchmark: prints how long Unite takes on 1000 circles; run by hand with --ignored"] fn timing_unite_1000_circles() { let mut seed = 0x1234_5678_u64; let mut rnd = || { @@ -971,8 +973,8 @@ fn timing_unite_1000_circles() { let circles: Vec = (0..1000).map(|i| shape(circle(rnd() * 1000.0, rnd() * 1000.0, 5.0 + rnd() * 30.0), i)).collect(); let t = std::time::Instant::now(); let r = pathfinder(PathfinderOp::Unite, &circles); + assert_eq!(r.len(), 1, "Unite gives one compound shape"); println!("unite 1000 circles: {} ms, {} anchors", t.elapsed().as_millis(), r[0].path.anchor_count()); - assert!(!r.is_empty()); } #[test] diff --git a/crates/pathops/tests/it/pathfinder_pinned.rs b/crates/pathops/tests/it/pathfinder_pinned.rs index 85f9ca423c..14fadbc6cb 100644 --- a/crates/pathops/tests/it/pathfinder_pinned.rs +++ b/crates/pathops/tests/it/pathfinder_pinned.rs @@ -1,7 +1,10 @@ //! The exact output of every Pathfinder operation, pinned so that work on the windings and the //! coverage tests can't change it: overlapping ellipses, rectangles and stars (even-odd and -//! non-zero, repeated keys for Merge) at a few counts. +//! non-zero, repeated keys for Merge) at a few counts. The filled regions of Unite, Minus Front, +//! Minus Back, Intersect and Exclude on the same inputs are also checked point by point against the +//! inputs' own coverage, so the pins do not rest on the sweep that computed them alone. +use kurbo::{BezPath, Shape as _}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes}; use vectorcraft_pathops::{PathfinderOp, Shape, pathfinder}; @@ -78,6 +81,62 @@ fn every_pathfinder_operation_is_pinned() { assert_eq!(got, PINNED); } +/// Whether an operation's output covers a point, from which inputs cover it. +type CoverRule = fn(&[bool]) -> bool; + +/// Shapes as kurbo paths with their fill rules. +type Filled = Vec<(BezPath, FillRule)>; + +fn inside(path: &BezPath, rule: FillRule, p: kurbo::Point) -> bool { + let w = path.winding(p); + match rule { + FillRule::NonZero => w != 0, + FillRule::EvenOdd => w % 2 != 0, + } +} + +#[test] +fn the_pinned_inputs_fill_what_their_coverage_says() { + use PathfinderOp::*; + // Which inputs cover a point decides whether each operation's output covers it. + let rules: [(PathfinderOp, CoverRule); 5] = [ + (Unite, |m| m.iter().any(|&c| c)), + (MinusFront, |m| m[0] && !m[1..].iter().any(|&c| c)), + (MinusBack, |m| m[m.len() - 1] && !m[..m.len() - 1].iter().any(|&c| c)), + (Intersect, |m| m.iter().all(|&c| c)), + (Exclude, |m| m.iter().filter(|&&c| c).count() % 2 == 1), + ]; + for (n, seed) in [(2, 3), (5, 7), (12, 11), (30, 13)] { + let input = shapes_of(n, seed); + let paths: Filled = input.iter().map(|s| (s.path.to_bezpath(), s.rule)).collect(); + let cover = |p: kurbo::Point| paths.iter().map(|(b, r)| inside(b, *r, p)).collect::>(); + let outputs: Vec<(PathfinderOp, CoverRule, Filled)> = + rules.iter().map(|&(op, rule)| (op, rule, pathfinder(op, &input).iter().map(|s| (s.path.to_bezpath(), s.rule)).collect())).collect(); + let (mut checked, mut filled) = (0, 0); + // A grid whose pitch shares no factor with the inputs' coordinates; points within 0.25 pt + // of an input edge are skipped, since the output's edge may sit there within the precision. + for i in 0..200 { + for j in 0..160 { + let p = kurbo::Point::new(-60.0 + f64::from(i) * 1.37, -60.0 + f64::from(j) * 1.37); + let m = cover(p); + let near_edge = [(0.25, 0.25), (-0.25, 0.25), (0.25, -0.25), (-0.25, -0.25)] + .iter() + .any(|&(dx, dy)| cover(kurbo::Point::new(p.x + dx, p.y + dy)) != m); + if near_edge { + continue; + } + checked += 1; + for (op, rule, out) in &outputs { + let got = out.iter().any(|(b, r)| inside(b, *r, p)); + assert_eq!(got, rule(&m), "{op:?} n={n} at {p:?}, covered by {m:?}"); + filled += usize::from(got); + } + } + } + assert!(checked > 10_000 && filled > 1_000, "n={n}: {checked} points, {filled} filled"); + } +} + /// Computed with the sweep of craft-libs 610c86792a, which places output curves closer to their /// inputs than the one before (craft-libs#721): every output keeps its shapes, subpaths and /// anchors, and its area and length agree with the earlier pins to 1e-6 relative. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 6ee43ef05d..e9d845756c 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -6,7 +6,7 @@ //! algorithm follows the compatibility ([`Encryption`]): 40-bit RC4 for PDF 1.3 (revision 2), //! 128-bit RC4 for PDF 1.4 (revision 3) and 1.5 (revision 4), 128-bit AES for 1.6 (revision 4) and //! 256-bit AES for 1.7 and 2.0 (revision 6). The random file key, salts and initialisation vectors -//! come from a SHA-256 stream seeded with the process's random hash keys, the time and the file +//! come from a SHA-256 stream seeded with the OS random source, the time and the file //! itself. A linearised file is encrypted between its two steps ([`protect_keeping`]): what //! encrypted it then encrypts the hint stream written last ([`Cipher`]). //! @@ -168,14 +168,49 @@ struct Entropy { counter: u64, } +/// What the OS random source returned, and the time. +type SeedSources = (Result<[u8; 32], getrandom::Error>, i64); + +#[cfg(test)] +thread_local! { + /// What the OS random source and the clock return to [`Entropy::new`] on this thread, when set. + pub(crate) static TEST_SEED_SOURCES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// 32 bytes from the OS random source, and the time. +fn seed_sources() -> SeedSources { + test_seed_sources().unwrap_or_else(|| { + let mut os = [0u8; 32]; + let os = getrandom::fill(&mut os).map(|()| os); + (os, vectorcraft_doc::metadata::now_unix().unwrap_or_default()) + }) +} + +/// What a test set in `TEST_SEED_SOURCES`. +#[cfg(test)] +fn test_seed_sources() -> Option { + TEST_SEED_SOURCES.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_seed_sources() -> Option { + None +} + impl Entropy { /// Seeded from the OS random source, with the time and `material` mixed in. fn new(material: &[&[u8]]) -> Result { - let mut os = [0u8; 32]; - getrandom::fill(&mut os).map_err(|e| failed(&format!("no random numbers ({e})")))?; + let (os, now) = seed_sources(); + Self::seeded(os, now, material) + } + + /// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes + /// into the seed, and a failed OS read is an error. + fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { + let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); - h.update(vectorcraft_doc::metadata::now_unix().unwrap_or_default().to_le_bytes()); + h.update(now.to_le_bytes()); for m in material { h.update((m.len() as u64).to_le_bytes()); h.update(m); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index bdf51da6f8..d6d68ee02b 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -915,6 +915,7 @@ mod tests { let (inks, alpha) = resampled_inks(inks, Some(alpha.clone()), &rule(&c, Kind::Color), (4, 1)).unwrap(); let alpha = alpha.unwrap(); let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + assert_eq!((inks.as_chunks::<4>().0.len(), alpha.len()), (4, 4), "{method}"); for (p, &a) in inks.as_chunks::<4>().0.iter().zip(&alpha) { assert!(a > 0 && p.iter().zip([40, 80, 120, 160]).all(|(&c, want)| m(c, a).abs_diff(m(want, a)) <= 1), "{method}: {p:?} at {a}"); } diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 70aacd89cf..cd40578cec 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -246,8 +246,13 @@ impl<'a> Device<'a> for Builder<'_> { // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft::pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); + // An inline image (no object of its own) is keyed by its samples too: the + // interpreter keys an image by its dictionary, the same for inline images of one + // size and encoding (#9247). + let inline = if st.dict().obj_id().is_none() { crate::import_scan::hash128(&*st.raw_data()) } else { 0 }; + let key = + craft::pdf::interpret::CacheKey::cache_key(&r) ^ inline ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). let known = !white && self.cmyk_keys.contains(&key); @@ -370,6 +375,9 @@ impl<'a> Device<'a> for Builder<'_> { None, ); let Some((px, w, h, sf)) = decoded else { return }; + // Keyed by its pixels too, as an inline raster image is by its samples: a stencil + // doesn't show its stream, and inline ones of one size share a dictionary (#9247). + let key = key ^ crate::import_scan::hash128(&px); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); match colorize { // Its own key: its pixels are the gray ones, whatever color paints it. diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 7c97651d1d..2dc6f1ec0a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -90,12 +90,12 @@ pub use import_shading::function_evaluation_limit; pub use marks::{leaves_out_bleed, page_bleed, printer_marks}; pub use output::ActiveProfiles; pub use page_widths::{FontWidths, PageWidths}; -#[cfg(any(test, feature = "read-count"))] -pub use pages::reads_of; pub use pages::{ IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript, open_pdf, read_illustrator_data_without_pdf_part, read_illustrator_data_without_pdf_part_with, }; +#[cfg(any(test, feature = "read-count"))] +pub use pages::{read_mark, reads_of, reads_of_since}; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; pub use print::*; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index a742070d20..7455c6d0f5 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -368,14 +368,33 @@ pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: & }) } -/// How many times each buffer has been read as a PDF, by its address (tests). +/// The number the next read as a PDF gets, and every read of a buffer by the buffer's address with +/// its number (tests). A freed buffer's reads stay under its address, so a later buffer at the same +/// address starts with them: count from a [`read_mark`] taken before that buffer exists. #[cfg(any(test, feature = "read-count"))] -static READS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +type Reads = (u64, std::collections::BTreeMap>); + +#[cfg(any(test, feature = "read-count"))] +static READS: std::sync::Mutex = std::sync::Mutex::new((0, std::collections::BTreeMap::new())); /// How many times `bytes`, at its address, has been read as a PDF on any thread (tests). #[cfg(any(test, feature = "read-count"))] pub fn reads_of(bytes: &[u8]) -> usize { - READS.lock().ok().and_then(|r| r.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) + READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(Vec::len)).unwrap_or(0) +} + +/// The number the next read as a PDF gets, for [`reads_of_since`] (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn read_mark() -> u64 { + READS.lock().map(|r| r.0).unwrap_or(0) +} + +/// How many times `bytes`, at its address, has been read as a PDF on any thread since `mark` was +/// taken with [`read_mark`] (tests). Reads made before `mark`, such as reads of a freed buffer +/// that had the same address, are not counted. +#[cfg(any(test, feature = "read-count"))] +pub fn reads_of_since(bytes: &[u8], mark: u64) -> usize { + READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(|reads| reads.iter().filter(|&&n| n >= mark).count())).unwrap_or(0) } /// [`open_with_options`] without looking at the file's objects ([`hostile`]): the reader builds its @@ -384,8 +403,9 @@ pub fn reads_of(bytes: &[u8]) -> usize { fn open_structural_with_options(bytes: &[u8], password: Option<&str>, options: &craft::pdf::OpenOptions) -> Result { #[cfg(any(test, feature = "read-count"))] if let Ok(mut reads) = READS.lock() { - let n = reads.entry(bytes.as_ptr() as usize).or_default(); - *n = n.saturating_add(1); + let n = reads.0; + reads.0 = n.saturating_add(1); + reads.1.entry(bytes.as_ptr() as usize).or_default().push(n); } if is_postscript(bytes) { return Err(PdfError::PostScript); @@ -763,4 +783,18 @@ mod tests { assert_eq!(super::decoded_size(1 << 30), "1 GB"); assert_eq!(super::decoded_size((1 << 30) + (1 << 20)), "1025 MB"); } + + /// Reads made before a mark, as of a freed buffer whose address a new one takes, are not + /// counted from that mark; reads after it are. + #[test] + fn reads_since_a_mark_leave_out_earlier_reads_at_the_same_address() { + let bytes = b"not a pdf".to_vec(); + let start = super::read_mark(); + let _ = super::open_structural_with_options(&bytes, None, &super::open_options()); + let mark = super::read_mark(); + assert_eq!(super::reads_of_since(&bytes, start), 1, "the read from the start"); + assert_eq!(super::reads_of_since(&bytes, mark), 0, "the read before the mark"); + let _ = super::open_structural_with_options(&bytes, None, &super::open_options()); + assert_eq!(super::reads_of_since(&bytes, mark), 1, "the read after the mark"); + } } diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index e29d828f48..7314e930ae 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -1034,6 +1034,19 @@ mod tests { assert!(unread.is_empty(), "{unread:#?}"); } + #[test] + fn a_hex_string_broken_by_a_non_hex_byte_hides_no_stream_after_it() { + // A `<` followed by hex digits and then a byte that is neither a hex digit nor white space + // is no hex string: the scan goes on from the next byte instead of skipping to a `>`. + let bad = b"<< /Type /XRef /DecodeParms 9 0 R >> stream\nx\nendstream"; + for lead in [&b"<4G "[..], b"<41 4z ", b"<\x00 "] { + let pdf = [lead, &bad[..]].concat(); + assert!(unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(&pdf)); + } + // A hex string that ends is skipped, and the stream after it is still read. + assert!(unsafe_file_streams(&[&b"<41 42> "[..], &bad[..]].concat())); + } + #[test] fn a_run_of_lt_in_an_image_a_string_or_a_comment_opens() { // #3924 review: every `<<` in a run of `<` (an image's flat area of grey 60) was read as a diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index c6b8772ff3..5e586bec6f 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -193,8 +193,26 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { #[test] fn the_file_key_is_seeded_from_the_os_random_source() { - // `RandomState` is no CSPRNG and its keys are fixed on the web: the seed must come from the OS. - let src = include_str!("../encrypt.rs"); - assert!(!src.contains("RandomState"), "encrypt.rs seeds its keys from RandomState"); - assert!(src.contains("getrandom::fill"), "encrypt.rs doesn't seed its keys from the OS random source"); + // The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so + // no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and + // other OS bytes alone give another stream. The exports set what the OS and the clock return. + use crate::encrypt::TEST_SEED_SOURCES; + let mut opts = PdfOptions::default(); + opts.settings.compatibility = Compatibility::Pdf20; + let plain = export(&doc(), &opts).unwrap(); + opts.settings.security = security("pw", "own"); + let protect_with = |os: Result<[u8; 32], getrandom::Error>| { + TEST_SEED_SOURCES.with(|c| c.set(Some((os, 1_700_000_000)))); + let out = protect(plain.clone(), &opts.settings); + TEST_SEED_SOURCES.with(|c| c.set(None)); + out + }; + let dict = |os: [u8; 32]| match protect_with(Ok(os)) { + Ok(bytes) => encrypt_dict(&bytes), + Err(e) => panic!("{e:?}"), + }; + assert_eq!(dict([7; 32]), dict([7; 32])); + assert_ne!(dict([7; 32]), dict([8; 32])); + // A failed OS read is an error, not a weaker seed. + assert!(protect_with(Err(getrandom::Error::UNSUPPORTED)).is_err()); } diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs index d0d1b949ab..b27dac4f0d 100644 --- a/crates/pdf/src/tests/file_fonts.rs +++ b/crates/pdf/src/tests/file_fonts.rs @@ -10,7 +10,7 @@ use kurbo::{Point, Rect, Shape}; use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject}; use vectorcraft_text::{FontDb, FontMatch}; -use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif}; +use crate::tests::live_text::{SOURCE_SERIF, outlines, renamed, texts, uninstalled_serif}; use crate::*; /// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes. @@ -274,3 +274,29 @@ fn two_glyphs_for_one_character_both_survive_import() { }; close(&glyph_ink(db, &imported), "imported"); } + +/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps: +/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that +/// type as outlines with the license warning instead of embedding the font again. +#[test] +fn a_restricted_font_the_file_carries_is_not_embedded_again() { + let mut font = renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif7"), ("Source Serif 4", "Source Serif 7")]); + let tables = usize::from(u16::from_be_bytes([font[4], font[5]])); + let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &font[*r..*r + 4] == b"OS/2").unwrap(); + let at = u32::from_be_bytes(font[os2 + 8..os2 + 12].try_into().unwrap()) as usize; + font[at + 8..at + 10].copy_from_slice(&0x0002u16.to_be_bytes()); + + let carried = import(&page_pdf(font)); + let t = texts(&carried.document); + assert!(t.iter().any(|t| t.file_fonts.is_some()), "the file's font draws its type"); + + let saved = export_with_report(&carried.document, &PdfOptions::default()).unwrap(); + assert!(saved.warnings.iter().any(|w| w.contains("Source Serif 7") && w.contains("doesn't allow embedding")), "{:?}", saved.warnings); + let back = import(&saved.bytes); + assert!( + texts(&back.document).is_empty(), + "no type in the saved file: {:?}", + texts(&back.document).iter().map(TextObject::plain_text).collect::>() + ); + assert!(!back.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font in the saved file"); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 0be8dce82f..5fdafeb5fc 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,39 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// Inline images with the same dictionary but other samples come in with their own pixels: the +/// stencil glyphs of a Type 3 font (#9247) and raster images on the page. +#[test] +fn inline_images_with_the_same_dictionary_keep_their_own_pixels() { + let n = first_extra(1); + let glyph = |hex: &str| { + stream("", &format!("1000 0 0 0 1000 1000 d1 q 1000 0 0 1000 0 0 cm BI /IM true /W 8 /H 8 /BPC 1 /D [1 0] /F /AHx ID\n{hex}>\nEI Q")) + }; + let objects = [ + format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>", + n + 1, + n + 2 + ), + glyph("1818181818181818"), + glyph("000000FFFF000000"), + ]; + let raster = |hex: &str| format!("q 10 0 0 10 0 0 cm BI /W 2 /H 1 /CS /RGB /BPC 8 /F /AHx ID\n{hex}>\nEI Q "); + let content = format!("BT /T3 24 Tf 10 30 Td (ab) Tj ET {}{}", raster("FF000000FF00"), raster("0000FFFFFFFF")); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let d = open(&one_page(&content, &format!("/Font << /T3 {n} 0 R >>"), &extra)); + let blobs: Vec>> = all(&d) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => Some(d.images[&im.key].bytes.clone()), + _ => None, + }) + .collect(); + assert_eq!(blobs.len(), 4, "two glyphs and two raster images"); + let distinct: std::collections::HashSet<&Arc>> = blobs.iter().collect(); + assert_eq!(distinct.len(), blobs.len(), "each image has its own pixels"); +} + /// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its /// resources, has its glyph procedures read once for the document. Each page still maps the font's /// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs diff --git a/crates/pdf/src/tests/import_options.rs b/crates/pdf/src/tests/import_options.rs index a419d64137..2205ae2a7f 100644 --- a/crates/pdf/src/tests/import_options.rs +++ b/crates/pdf/src/tests/import_options.rs @@ -272,7 +272,8 @@ fn a_page_without_area_gets_the_size_viewers_give_it() { let bytes = pdf(&[PdfPage { media: [0.0, 0.0, 0.0, 0.0], ..PdfPage::new(0.0, 0.0, "") }], None); let i = info(&bytes, None).unwrap(); let (w, h) = (i.pages[0].width, i.pages[0].height); - assert!(w > 0.0 && h > 0.0); + // US Letter, 8.5 × 11 in. + assert_eq!((w, h), (612.0, 792.0)); for crop in [CropTo::Crop, CropTo::Media, CropTo::Art] { let ab = open(&bytes, ImportOptions { crop, ..Default::default() }).artboards[0].rect; assert_eq!((ab.width(), ab.height()), (w, h), "{crop:?}"); diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 90341ca28b..b60f426834 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -271,7 +271,7 @@ fn invisible_text_is_type_whatever_its_glyphs_look_like() { } /// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16. -fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { +pub(crate) fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { let mut bytes = font.to_vec(); let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); for &(from, to) in names { @@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() { let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); vectorcraft_text::layout(db, &t).glyphs.len() == 1 }; - // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + // An installed Arabic font with a lam-alef ligature. The test checks that its type comes + // back, so the choice of font does not depend on the import. let Some(face) = preferred .iter() .chain(&db.families()) .filter_map(|f| db.face(f, "Regular")) - .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) - .find(|f| !imported_texts(f, "بب").is_empty()) + .find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) else { return; // No such font on this host. }; diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index cf8ad25e3b..b2e8ecb2f6 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -73,11 +73,14 @@ fn a_cmyk_mesh_is_written_smooth_in_its_inks() { let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); let (meshes, paths) = kinds(&back); assert!(meshes >= 1 && paths <= 4, "meshes {meshes}, paths {paths}"); + let mut points = vec![]; back.walk(|n| { if let NodeKind::Mesh(m) = &n.kind { - assert!(m.points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })), "{:?}", m.points); + points.extend(m.points.iter().map(|p| p.color)); } }); + assert!(!points.is_empty(), "the meshes have points"); + assert!(points.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{points:?}"); assert_similar(&render_artboard(&d), &render_artboard(&back), 6.0, 0.02); } diff --git a/crates/pdf/src/tests/realtext.rs b/crates/pdf/src/tests/realtext.rs index 7fcd06dd56..5f4ef0205f 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva /// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either, /// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped -/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida, -/// or when PDF text import returns no strings on this platform. +/// without an OpenType font that covers Arabic and the tatweel. #[test] fn kashidas_are_not_written_as_hyphens() { let db = FontDb::global(); @@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() { t.para.justify = vectorcraft_doc::Justify::JustifyAll; t.para.kashida = vectorcraft_doc::text::Kashida::Medium; let tatweel = face.glyph_for('\u{0640}'); - if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) { - return; - } + assert!( + vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel), + "{}: justified layout inserts a kashida", + face.family + ); let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)); - if back.is_empty() { - return; - } + assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family); assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}"); // Every letter comes back, at least as often as the text holds it (the justified words may // come back as type objects of their own). let all = back.concat(); - if all.is_empty() { - return; - } let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count(); for c in text.chars().filter(|c| c.is_alphabetic()) { assert!(count(&all, c) >= count(text, c), "{c}: {back:?}"); diff --git a/crates/pdf/src/tests/spread.rs b/crates/pdf/src/tests/spread.rs index ebfe655f9a..0a852ba664 100644 --- a/crates/pdf/src/tests/spread.rs +++ b/crates/pdf/src/tests/spread.rs @@ -236,17 +236,21 @@ fn a_perceptual_spot_gradient_too_long_once_repeated_is_an_image() { } } -/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked. +/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked, as the +/// same gradient that pads does. #[test] fn a_spread_gradient_without_stops_exports() { for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let mut d = Document::new(200.0, 200.0); - let (l, id) = (d.layers[0].id, d.alloc_id()); - let ap = Appearance::basic(paint.clone(), paint, 4.0); - d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); - export(&d, &PdfOptions::default()).unwrap(); + let written = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + let mut d = Document::new(200.0, 200.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let ap = Appearance::basic(paint.clone(), paint, 4.0); + d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); + uncompressed(&d, &PdfOptions { created: Some(0), ..PdfOptions::uncompressed() }) + }; + assert_eq!(written(GradientSpread::Repeat), written(GradientSpread::Pad), "{kind:?}"); } } diff --git a/crates/pdf/src/tests/stroke.rs b/crates/pdf/src/tests/stroke.rs index d57cbc42d0..881ebd4a4c 100644 --- a/crates/pdf/src/tests/stroke.rs +++ b/crates/pdf/src/tests/stroke.rs @@ -90,5 +90,6 @@ fn line_and_head_share_one_opacity_group() { _ => {} }); assert!(group_opacity.is_some_and(|o| (o - 0.5).abs() < 0.01), "{group_opacity:?}"); + assert!(!leaf_opacities.is_empty(), "the line and its head come back as paths"); assert!(leaf_opacities.iter().all(|o| (o - 1.0).abs() < 1e-3), "{leaf_opacities:?}"); } diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 31ea411840..f64f8c4173 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -745,7 +745,7 @@ fn text_heavy(columns: usize, rows: usize) -> Vec { /// How long a text-heavy file takes to open as type (run by hand: `-- --ignored --nocapture`). #[test] -#[ignore] +#[ignore = "timing, run by hand"] fn perf_text_heavy_open() { let bytes = text_heavy(20, 200); for _ in 0..2 { diff --git a/crates/pdf/tests/gradient_forms.rs b/crates/pdf/tests/gradient_forms.rs index 7373ec8494..a904935fe5 100644 --- a/crates/pdf/tests/gradient_forms.rs +++ b/crates/pdf/tests/gradient_forms.rs @@ -159,6 +159,7 @@ mod quartz { } /// Quartz places RGB and CMYK radial centres, edges and masks with their translated art. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() { for mode in [ColorMode::Rgb, ColorMode::Cmyk] { @@ -179,6 +180,7 @@ mod quartz { } /// Quartz retains the linear ramp's direction inside forms on a translated artboard. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_linear_gradient_directions_in_forms() { for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) { @@ -190,6 +192,7 @@ mod quartz { } /// A gradient's stop-opacity mask remains aligned with its colour through nested forms. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() { let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN); diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 621f5e79bc..aecb0bd533 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -44,3 +44,7 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] } [features] # `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only). test-steady = [] + +# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate. +[package.metadata.craft] +reads-every-member = true diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index a78aeec09b..f7cf875a6c 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -330,13 +330,11 @@ mod tests { use super::*; #[test] - fn names_round_trip_and_serialize_as_names() { - for p in ALL { - assert_eq!(Permission::parse(p.name()), Some(p)); - assert_eq!(serde_json::to_value(p).unwrap(), serde_json::json!(p.name())); - } + fn names_parse_and_serialize_as_names() { + assert_eq!(serde_json::to_value(ALL).unwrap(), serde_json::json!(names(&ALL)), "saved names are the names"); + assert_eq!(Permission::parse("doc.write"), Some(Permission::DocWrite)); assert_eq!(Permission::parse("document.read"), None); - assert!(RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); + assert!(!RESERVED.is_empty() && RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); } #[test] diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index fafb1b188f..299d6d627a 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -61,7 +61,13 @@ pub(crate) fn effect_bounds_with( /// reach of its own and its members' raster effects, measured as [`Node::visual_bounds_with`] /// measures art without effects: what Object › Rasterize makes its image over. pub fn drawn_bounds(doc: &Document, n: &Node) -> Option { - fx::painted_reach(&doc.symbol_boxes(), n) + drawn_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`drawn_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option { + fx::painted_reach(symbols, n) } /// For a path or compound path whose own Rasterize effect is followed by Transform effects that diff --git a/crates/render/src/encode/tests_bmp.rs b/crates/render/src/encode/tests_bmp.rs index f458c1999b..64d3ecdb55 100644 --- a/crates/render/src/encode/tests_bmp.rs +++ b/crates/render/src/encode/tests_bmp.rs @@ -133,6 +133,7 @@ fn greys_and_impossible_combinations() { let px = art(w, h); for depth in [8, 24] { let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), craft_image_codecs::Format::Bmp); + assert_eq!(img.dimensions(), (w, h), "depth {depth}"); assert!(img.pixels().all(|p| p[0] == p[1] && p[1] == p[2]), "depth {depth}: greys"); } let bad = [ diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 413781de13..375dcaf15a 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -164,15 +164,18 @@ fn colour_models_write_their_components_and_profiles() { #[test] fn model_and_method_ids_round_trip() { - for m in ColorModel::ALL { - assert_eq!(ColorModel::from_id(m.id()), Some(m)); - assert_eq!(ColorModel::from_id(m.label()), Some(m)); - } + // Saved options name a model or a method by id or label, in any case. + assert_eq!(ColorModel::from_id("cmyk"), Some(ColorModel::Cmyk)); + assert_eq!(ColorModel::from_id("RGB"), Some(ColorModel::Rgb)); + assert_eq!(ColorModel::from_id("gray"), Some(ColorModel::Gray)); + assert_eq!(ColorModel::from_id("Grayscale"), Some(ColorModel::Gray)); assert_eq!(ColorModel::from_id("grey"), Some(ColorModel::Gray)); - for m in Method::ALL { - assert_eq!(Method::from_id(m.id()), Some(m)); - } + assert_eq!(ColorModel::from_id("lab"), None); + assert_eq!(Method::from_id("optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("baseline optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("Progressive"), Some(Method::Progressive)); assert_eq!(Method::from_id("bogus"), None); + assert_eq!(Method::from_id(""), None); } /// A 20×10 pt document: a black-ink rectangle on the left half, an RGB red one on the right. diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 837c62f359..d4067fc743 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -245,12 +245,17 @@ fn gif_decodes() { #[test] fn ids_round_trip() { - for r in Reduction::ALL { - assert_eq!(Reduction::from_id(r.id()), Some(r)); - } - for d in Dither::ALL { - assert_eq!(Dither::from_id(d.id()), Some(d)); - } + // Saved options name a reduction or a dither by id or label, in any case. + assert_eq!(Reduction::from_id("blackWhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("blackwhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("Black & White"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("selective"), Some(Reduction::Selective)); + assert_eq!(Reduction::from_id("restrictive"), None); + assert_eq!(Dither::from_id("none"), Some(Dither::None)); + assert_eq!(Dither::from_id("No Dither"), Some(Dither::None)); + assert_eq!(Dither::from_id("PATTERN"), Some(Dither::Pattern)); + assert_eq!(Dither::from_id("bayer"), None); + assert_eq!(Dither::from_id(""), None); } /// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 757290ed1f..f843ce01f7 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -371,9 +371,16 @@ fn per_stroke_raster_effects_use_the_single_threaded_pipeline() { } d.remove(id).unwrap(); d.insert(Some(l), 0, n).unwrap(); - let mut r = Renderer::new(); - r.threads = 4; - let _ = r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + let draw = |threads| { + let mut r = Renderer::new(); + r.threads = threads; + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()) + }; + let (threaded, single) = (draw(4), draw(1)); + // The stroke's glow shows outside it: red, where nothing else is drawn. + let glow = threaded.pixel(40, 14); + assert!(glow[3] > 0 && glow[0] > glow[1] && glow[0] > glow[2], "{glow:?}"); + assert!(threaded.pixels == single.pixels, "four threads draw what one does"); } #[test] @@ -1966,7 +1973,7 @@ fn rasters_made_over_moved_rasters_count_as_moved() { /// Reproduce #1257's moving, filtered rectangle: the first frame renders as before a drag, /// and the next eight render as the canvas renders a drag's frames (`interacting`). Then the /// eighth position renders as the canvas renders the frame after the drag, and that frame -/// renders once more with every raster cached. +/// renders once more with every raster cached. Both draw what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render texture_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2004,10 +2011,12 @@ fn texture_drag_perf() { } let mut time = |o: &RenderOptions| { let start = std::time::Instant::now(); - std::hint::black_box(r.render(&doc, 1800, 1500, view, o)); - start.elapsed().as_secs_f64() * 1000.0 + let image = r.render(&doc, 1800, 1500, view, o); + (start.elapsed().as_secs_f64() * 1000.0, image.pixels) }; - let (after, again) = (time(&opts), time(&opts)); + let ((after, after_px), (again, again_px)) = (time(&opts), time(&opts)); + let fresh = Renderer::new().render(&doc, 1800, 1500, view, &opts).pixels; + assert!(after_px == fresh && again_px == fresh, "{effect}: the frame after the drag draws what a fresh renderer draws"); ms.sort_by(f64::total_cmp); println!( "{effect}: moved CMYK rounded rectangle at 190.07%, DPI 1.5, 1800x1500: median {:.2} ms; samples {ms:?}; the frame after the drag {after:.2} ms, that frame again {again:.2} ms", @@ -2020,7 +2029,7 @@ fn texture_drag_perf() { /// view centered on the rectangle: the first frame renders as before a drag, and the next eight /// render as a drag's frames, once with `interacting` alone and once with `dragging` as well (as /// the canvas renders them). Then the eighth position renders as the canvas renders the frame -/// after the drag. The hashes of that frame and of a fresh renderer's frame compare builds. +/// after the drag, which draws what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render zoomed_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2030,12 +2039,6 @@ fn zoomed_drag_perf() { ("Gaussian Blur 8 pt", vec![("blur.gaussian", json!({"radius": 8}))]), ("Drop Shadow and Craquelure", vec![("stylize.dropShadow", json!({"blur": 7})), ("texture.craquelure", json!({}))]), ]; - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; for (name, effects) in sets { for zoom in [1.0, 4.0, 16.0, 64.0] { let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), effects.clone()); @@ -2062,15 +2065,14 @@ fn zoomed_drag_perf() { let still = r.render(&doc, 2560, 1440, view, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, 2560, 1440, view, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x, dragging {dragging}: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 457c4c48c8..544438d96f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -294,7 +294,9 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; +pub use bounds::{ + drawn_bounds, drawn_bounds_with, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage, +}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index cd5cacac97..93fe88a1ed 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); - if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) { return band; } let outline = effects::stroke::line_outline(line, st, width, fine); @@ -49,21 +49,65 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) } +/// The points where `line` has a corner: where two of its segments meet with tangents that are not +/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in +/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the +/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each. +fn corners(line: &BezPath) -> Vec> { + let tangents = |seg: PathSeg| { + let c = match seg { + PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1), + other => cubic(other)?, + }; + Some((start_tangent(&c)?, end_tangent(&c)?)) + }; + let mut out = Vec::new(); + // A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted. + for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() { + let mut here = Vec::new(); + let n = sub.segs.len(); + let first = if sub.closed { 0 } else { 1 }; + for i in first..n { + let before = if i == 0 { n - 1 } else { i - 1 }; + let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue }; + let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) { + (Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(), + _ => false, + }; + if !smooth { + here.push(b.start()); + } + } + here.sort_by(point_order); + out.push(here); + } + out +} + +/// Points in order of `x`, then `y` ([`corners`]). +fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering { + a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)) +} + /// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill /// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet -/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the -/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the +/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for +/// each subpath of `lines`, [`corners`]) and a round join where the lines a +/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as /// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a /// point that isn't finite, or is closed and no wider or taller than the stroke: those take /// [`effects::stroke::line_outline`]. -fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { +fn thin_band(lines: &BezPath, corners: &[Vec], st: &StrokeLayer, width: f64, fine: f64) -> Option { let h = width / 2.0; // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); let mut out = BezPath::new(); let mut pts: Vec = Vec::new(); let mut closed = false; - let flush = |pts: &mut Vec, closed: bool, out: &mut BezPath| -> Option<()> { + // The subpath being read; `None` before the first move. + let mut sub: Option = None; + let flush = |pts: &mut Vec, closed: bool, sub: Option, out: &mut BezPath| -> Option<()> { if pts.is_empty() { return Some(()); } @@ -80,14 +124,15 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option return None; } } - band_sub(out, pts, closed, st, h, step); + band_sub(out, pts, corners.get(sub?)?, closed, st, h, step); pts.clear(); Some(()) }; for el in lines.elements() { match *el { PathEl::MoveTo(p) => { - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; + sub = Some(sub.map_or(0, |s| s + 1)); closed = false; pts.push(p); } @@ -100,7 +145,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, } } - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; Some(out) } @@ -108,8 +153,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option /// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, /// the end cap, its right side backward and the start cap; for a closed one its left side and its /// right side backward, as two contours. `h` is half the width and `step` the angle between the -/// points of a round join or cap. -fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { +/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's +/// `corners` (sorted by [`point_order`]) and a round join elsewhere. +fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { use vectorcraft_doc::{LineCap, LineJoin}; let n = pts.len(); let chords = if closed { n } else { n - 1 }; @@ -143,7 +189,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: inner.push(p); inner.push(p - nb * sign); outer.push(p + na * sign); - match st.join { + // Only the path's corners take the stroke's join; where the lines of a curve turn sharply + // the stroke along the curve is round. + let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round }; + match kind { LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), LineJoin::Miter | LineJoin::Bevel => {} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index eddc139ebb..99ee9a5f0c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -190,7 +190,8 @@ fn linear_gradient_goes_white_to_black() { assert!(r.pixel(2, 50)[0] > 240); assert!(r.pixel(97, 50)[0] < 15); let m = r.pixel(50, 50)[0] as i32; - assert!((m - 128).abs() < 12, "{m}"); + // Pixel centre x = 50.5: 255 · (1 - 0.505) = 126. + assert!((m - 126).abs() <= 2, "{m}"); } #[test] diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index a69ac094ae..28adeba7c2 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -275,12 +275,19 @@ fn short_dashed_strokes_are_outlined_whole() { let one = BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(100.0, 100.0))]); let mut dot = one.clone(); dot.line_to((100.0, 100.0)); - for (what, bp) in - [("empty", BezPath::new()), ("one anchor", one), ("one anchor, closed on itself", dot), ("a ring of 40 anchors", ring(40, 80.0))] - { + // The ring is outlined once; the degenerate paths only have to draw what a whole outline draws. + for (what, bp, ring_of_40) in [ + ("empty", BezPath::new(), false), + ("one anchor", one, false), + ("one anchor, closed on itself", dot, false), + ("a ring of 40 anchors", ring(40, 80.0), true), + ] { let d = doc(&bp, st.clone()); let mut r = Renderer::new(); let img = render(&mut r, &d, Point::new(100.0, 100.0)); + if ring_of_40 { + assert_eq!(r.strokes.len(), 1, "{what}: one outline"); + } assert!(r.strokes.values().all(|e| e.crop.is_none()), "{what}: outlined whole"); assert!(img.pixels == whole(&d, Point::new(100.0, 100.0)).pixels, "{what}: the same pixels"); } @@ -393,6 +400,7 @@ fn a_stroke_a_wide_stroke_crosses_over_stays_whole() { let at = Point::new(20_000.0, 2.0); let mut r = Renderer::new(); let img = render(&mut r, &d, at); + assert_eq!(r.strokes.len(), 1, "one outline"); assert!(r.strokes.values().all(|e| e.crop.is_none())); assert!(img.pixels == whole(&d, at).pixels); } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 7b68bc74d4..8579c314b8 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2455,8 +2455,8 @@ fn proof_previews_draw_changes_as_a_new_renderer_does() { } /// A thumbnail of an object under a filter that treats color channels apart (Color Halftone) is -/// made again when the document's color mode changes: CMYK documents screen ink channels, RGB -/// documents light ones. +/// made again when the document's color mode changes. RGB documents screen three ink planes. +/// CMYK documents screen four ink planes. #[test] fn filtered_thumbnails_follow_the_color_mode() { let _fonts = fonts_steady(); @@ -2464,9 +2464,9 @@ fn filtered_thumbnails_follow_the_color_mode() { let mut d = Document::new(200.0, 100.0); d.color_mode = vectorcraft_doc::ColorMode::Cmyk; let halftone = effect("pixelate.colorHalftone", serde_json::json!({"maxRadius": 4})); - let orange = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(1.0, 0.5, 0.0)), vec![halftone]); - let id = orange.id; - let mut d = with_art(d, vec![orange]); + let gray = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(0.5, 0.5, 0.5)), vec![halftone]); + let id = gray.id; + let mut d = with_art(d, vec![gray]); let mut r = Renderer::new(); let before = r.render_thumbnail(&d, id, 128).unwrap().pixels; d.color_mode = vectorcraft_doc::ColorMode::Rgb; @@ -2662,6 +2662,7 @@ fn a_reduced_cmyk_image_paints_its_own_inks() { let d = cmyk_doc_with("inks", blob, 8, 8); let on = RenderOptions { image_mips: true, ..Default::default() }; let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 8.0, 8.0), 0.25, &on); + assert_eq!(inks.len(), 2 * 2 * 4, "2 × 2 pixels of four inks"); for px in inks.as_chunks::<4>().0 { assert!(px.iter().zip(ink).all(|(a, b)| a.abs_diff(b) <= 1), "{px:?} vs {ink:?}"); } @@ -2805,6 +2806,7 @@ fn a_tiled_image_draws_what_the_whole_image_draws() { let plane = |ink| ink::ink_image(&key, &full, ink, d.images.get("seams"), false).1; let bytes = |pm: &Pixmap| pm.data().iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect::>(); let whole = ink::amounts(&bytes(&plane(Ink::Cmy)), &bytes(&plane(Ink::K))); + assert_eq!(drawn.len(), 300 * 40 * 4, "300 × 40 pixels of four inks"); for (i, got) in drawn.as_chunks::<4>().0.iter().enumerate() { let (x, y) = (x0 as usize + i % 300, i / 300); let want = &whole[(y * w as usize + x) * 4..][..4]; diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 4017448fd9..ab31619111 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -133,6 +133,148 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); } +/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles +/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001. +fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec) { + let path = close_smooth_path(gap, handle, zoom); + let mut line = Vec::new(); + vectorcraft_geom::flatten(path.iter(), 1e-3, |el| { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el { + line.push(p); + } + }); + (path, line) +} + +/// How far `q` is from the nearest point of `path`. +fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 { + use kurbo::ParamCurveNearest; + path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) +} + +/// The path of [`close_smooth_anchors`]. +fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath { + use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath}; + let dir = kurbo::Vec2::new(0.8, 0.6); + let mut anchors = vec![ + Anchor::corner(kurbo::Point::new(0.0, 0.0)), + Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)), + ]; + let mut x = 10.0; + for i in 0..6 { + x += gap; + let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap); + anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth }); + } + anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0))); + kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath() +} + +/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its +/// outline has no point farther than a stroke's width from the curve, and covers the curve. The +/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting +/// them drew the stroke's miter joins as spikes. +#[test] +fn thin_strokes_follow_smooth_anchors_close_together() { + for gap in [0.1, 1.0] { + let (path, line) = close_smooth_anchors(gap, 1.0, 1.0); + for w in [0.6, 0.9] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve"); + } + } + for p in line.iter().step_by(7) { + assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered"); + } + } + } +} + +/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is +/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter. +/// 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}"); + } + } + } +} + +/// A thin stroke along smooth anchors close together, with handles long beside the gaps between +/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels +/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter +/// joins drawn where the curve's lines turned sharply covered points well outside the stroke. +#[test] +fn thin_strokes_along_long_handles_cover_the_curve_outline() { + let tol = 0.25; + for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] { + let path = close_smooth_path(gap, 10.0, 4.0); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let fine = (tol / 8.0).min(w / 32.0); + let mut want = BezPath::new(); + vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el)); + let bb = want.bounding_box().inflate(w, w); + for i in 0..90 { + for j in 0..90 { + let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0); + let d = from_curve(&path, q); + if (d - w / 2.0).abs() > 0.25 { + assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve"); + } + } + } + } +} + +/// A corner of one subpath does not change the join where the lines of another subpath's curve +/// meet at the same point: the first subpath's outline is the same with or without the second. +#[test] +fn thin_strokes_take_corners_from_their_own_subpath() { + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + let mut alone = BezPath::new(); + alone.move_to((-1.0, 0.0)); + alone.line_to((0.0, 0.0)); + alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0)); + let mut both = alone.clone(); + both.move_to((-10.0, -10.0)); + both.line_to((0.0, 0.0)); + both.line_to((-10.0, 10.0)); + let one = raster_stroke_outline(&alone, &st, w, 0.25); + let two = raster_stroke_outline(&both, &st, w, 0.25); + assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline"); +} + /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. #[test] diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 0087c1a4a8..0a69d9ba3c 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -420,18 +420,11 @@ fn a_shadow_over_a_cropped_shadow_keeps_to_the_earlier_ones_margin() { /// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as /// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas -/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's -/// frame compare builds. +/// renders them), then the frame after the drag, which draws what a fresh renderer draws. /// Run with `cargo test --release -p vectorcraft-render backdrop_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] fn backdrop_drag_perf() { - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; let size = (2560, 1440); for (name, effects, zoom) in cases() { let (base, id) = backdrop(&effects); @@ -455,15 +448,14 @@ fn backdrop_drag_perf() { let still = r.render(&doc, size.0, size.1, xf, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, size.0, size.1, xf, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/render/tests/it/golden.rs b/crates/render/tests/it/golden.rs index a9dcb7af63..1a9fc61948 100644 --- a/crates/render/tests/it/golden.rs +++ b/crates/render/tests/it/golden.rs @@ -49,7 +49,8 @@ fn linear_gradient_left_to_right() { assert_rgb(&img, 1, 50, [255, 0, 0], 12); assert_rgb(&img, 98, 50, [0, 0, 255], 12); let mid = img.over_white(50, 50); - assert!(mid[0].abs_diff(128) < 20 && mid[2].abs_diff(128) < 20 && mid[1] < 10, "mid {mid:?}"); + // Pixel centre x = 50.5: red 255 · 0.495 = 126, blue 255 · 0.505 = 129. + assert!(mid[0].abs_diff(126) <= 2 && mid[2].abs_diff(129) <= 2 && mid[1] <= 2, "mid {mid:?}"); // Red decreases monotonically along x; rows are identical (horizontal gradient). let reds: Vec = (0..100).step_by(5).map(|x| img.over_white(x, 50)[0]).collect(); assert!(reds.windows(2).all(|w| w[1] <= w[0]), "{reds:?}"); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b7156550c8..4e9a9bf2e3 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -277,6 +277,65 @@ struct Assign { after_new: bool, } +/// `name = {`: an object literal assigned to a variable. +struct ObjectValue { + name: String, + /// The bracket depth inside its `{`. + depth: usize, + /// The document methods writing a file that it defines with a single function expression as the + /// key's whole value, a bit each ([`Analyzer::writers`]). + bits: u8, + /// It is the value of the first name a `var` statement declares, and the statement is directly + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or + /// a loop's parentheses: only then does the variable hold `bits` after it. + whole: bool, + /// The bit of the method whose value is being read, and how far that value has been read. + value: Option<(u8, Value)>, +} + +/// How far the value of an object literal's key that names a document method writing a file has been +/// read, by the tokens directly inside the literal's braces. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Value { + /// `function`. + Function, + /// The function expression's name. + Name, + /// The `(` of its parameters. + Params, + /// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes + /// next. + Body, + /// Anything else, or anything after the body. + Other, +} + +impl ObjectValue { + /// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value + /// being read, and gives the literal the method only when the value is a single function + /// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give + /// it nothing). + fn step(&mut self, t: &Sig) { + let Some((bit, value)) = self.value else { return }; + if t.is(",") || t.is("}") { + if value == Value::Body { + self.bits |= bit; + } else { + self.bits &= !bit; + } + self.value = None; + return; + } + let next = match value { + Value::Function if t.kind == T::Ident => Value::Name, + Value::Function | Value::Name if t.is("(") => Value::Params, + Value::Params if t.is("{") => Value::Body, + _ => Value::Other, + }; + self.value = Some((bit, next)); + } +} + /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it /// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { @@ -416,6 +475,10 @@ struct Chain { group: Option, } +/// Characters a member chain holds at least, more than the longest chain the checks compare +/// (`app.documents.addDocumentNoUI().print()` has 39). +const CHAIN_CHARS: usize = 64; + impl Chain { fn new(root: String, bare: bool, line: usize) -> Self { let (chars, cut) = (root.chars().count(), root.ends_with('…')); @@ -464,6 +527,42 @@ impl Chain { self.last_change = false; self.append(if call { "()" } else { "[]" }, cap); } + + /// The index that ends the chain is of the member `name`, which a string literal in brackets + /// named: `[]` becomes `.name` when one of [`catalog::DOM_DOCUMENTS`] reads that member as a + /// property (`app['activeDocument']`, `app['documents'][0]`). Any other name keeps the index. + fn name_index(&mut self, name: &str, cap: usize) { + let Some(base) = self.path.strip_suffix("[]").filter(|_| !self.cut) else { return }; + let property = |d: &&str| { + d.strip_prefix(base) + .and_then(|m| m.strip_prefix('.')) + .and_then(|m| m.strip_prefix(name)) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('[')) + }; + let ident = !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$'); + if !ident || !catalog::DOM_DOCUMENTS.iter().any(property) { + return; + } + self.path.truncate(self.path.len() - 2); + self.chars = self.chars.saturating_sub(2); + self.last_change = false; + for s in [".", name] { + self.append(s, cap); + } + } + + /// The call that ends the chain is of the member `name`, which a string literal in brackets + /// named: `[]()` becomes `.name()`. + fn name_call(&mut self, name: &str, cap: usize) { + if self.cut || !self.path.ends_with("[]()") { + return; + } + self.path.truncate(self.path.len() - 4); + self.chars = self.chars.saturating_sub(4); + for s in [".", name, "()"] { + self.append(s, cap); + } + } } /// A function body being read: the bracket depth inside it, and what each name declared in it @@ -472,6 +571,8 @@ impl Chain { /// member chain or a File object assigned in it to an outer name stays. struct Scope { depth: usize, + /// The offset of the body's `{` in the text, which [`Declared::looped`] names it by. + start: usize, saved: HashMap, /// The bracket depth of the `var` statement the body is in, if any: it goes on when the body /// closes. @@ -507,6 +608,8 @@ struct Saved { shadowed: Option, /// It was a platform name the script had a meaning of its own for. own: bool, + /// What it held in [`Analyzer::writers`], 0 for nothing. + writer: u8, } /// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are @@ -556,6 +659,8 @@ struct Analyzer<'s, 'a, 'l> { file: Option<&'a str>, /// The four significant tokens before this one, the latest first. h: [Option>; 4], + /// The significant token before the four of [`Self::h`]. + h4: Option>, brackets: Brackets, /// Nesting too deep to follow was reported: it is reported once. deep: bool, @@ -578,6 +683,25 @@ struct Analyzer<'s, 'a, 'l> { maybe_files: HashSet, /// `maybe_files` ran out of room: no variable counts as holding a Folder object. maybe_files_full: bool, + /// The variables holding an object literal of the script's own that defines a method named as a + /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit + /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. + writers: HashMap, + /// The object literals being assigned to a variable, the innermost last, up to + /// [`crate::Limits::nesting`] of them. + objects: Vec, + /// An object literal whose `}` the last token was, with the methods it defines: the variable + /// holds them when the next token ends the `var` statement's value. + closed: Option<(String, u8)>, + /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver + /// that is not such a variable. + index_receiver: u8, + /// The variables that may get another value when code read elsewhere runs: assigned inside a + /// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]). + /// None of them joins [`Analyzer::writers`]. + later: HashSet, + /// `later` ran out of room: no variable joins [`Analyzer::writers`]. + later_full: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -641,6 +765,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { acc, file, h: [None; 4], + h4: None, brackets: Brackets::default(), deep: false, active: None, @@ -654,6 +779,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // property of the global object. maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(), maybe_files_full: false, + writers: HashMap::new(), + objects: vec![], + closed: None, + index_receiver: 0, + later: HashSet::new(), + later_full: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -738,6 +869,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or // closes a function body. self.settle_groups(&t); + self.settle_literal(&t); // A line break ends a `var` statement when it is outside the statement's brackets, and the // tokens on either side of it don't go on with the expression. if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) { @@ -760,18 +892,26 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.group_step(&t, started, before); self.paren_step(&t, before); self.assignment(&t, started); + self.object_key(&t, before); self.features(&t); self.newer(&t); self.module_check(&t); + self.h4 = self.h[3]; self.h = [Some(t), self.h[0], self.h[1], self.h[2]]; } // ---------- member chains ---------- + /// The most characters a member chain holds while it is read: [`crate::Limits::echo`], and at least + /// [`CHAIN_CHARS`], so a short echo limit cuts only the chains the report lists. + fn chain_cap(&self) -> usize { + self.acc.limits.echo.max(CHAIN_CHARS) + } + /// Whether the active chain takes `t` (a `.`, a member's name, `[` or `(`); any other token ends /// it. fn continue_chain(&mut self, t: &Sig<'s>) -> bool { - let cap = self.acc.limits.echo; + let cap = self.chain_cap(); let Some(c) = self.active.as_mut() else { return false }; if c.after_dot { c.after_dot = false; @@ -859,6 +999,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } @@ -868,6 +1009,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if !folder && !self.maybe_files.contains(&name) { if self.acc.room(self.maybe_files.len()) { self.maybe_files.insert(name.clone()); @@ -991,6 +1133,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed, own: self.own_names.contains(name), + writer: self.writers.get(name).copied().unwrap_or(0), } } @@ -1025,6 +1168,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.own_names.remove(&name); } + // An outer variable the body assigned keeps only the methods it still has: the body may have + // given it another value. + let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) }; + if writer != 0 { + self.writers.insert(name.clone(), writer); + } else { + self.writers.remove(&name); + } if let Some(hidden) = saved.shadowed && let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name) && let Some(s) = self.shadowed.get_mut(i) @@ -1074,6 +1225,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.bound.remove(name); self.files.remove(name); self.folders.remove(name); + self.writers.remove(name); self.hide_root(name); } @@ -1134,7 +1286,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if body { let params = self.params.take().map(|(_, names)| names).unwrap_or_default(); if self.scopes.len() < self.acc.limits.nesting { - self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() }); + self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() }); // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); @@ -1156,6 +1308,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } if self.suspended.last().is_some_and(|c| c.wait == self.depth()) { self.active = self.suspended.pop(); + // `app['activeDocument']`: a string literal in the brackets names a member. + if t.text == "]" + && is(self.h[1], "[") + && let Some(name) = self.h[0].filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + { + let cap = self.chain_cap(); + if let Some(c) = self.active.as_mut() { + c.name_index(&name, cap); + } + } } self.close_scopes(); let grouped = self.close_parens(t); @@ -1267,6 +1429,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name), + writer: 0, }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { @@ -1290,6 +1453,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); + } else if !a.after_new && t.is("{") { + // An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]). + self.unbind(&a.name); + let [_, _, declaration, before] = self.h; + let depth = self.depth(); + let body = self.scopes.last().map_or(0, |s| s.depth); + let starts = before.is_none() + || [";", "{", "}"].iter().any(|p| is(before, p)) + // A line break after a label's `:` does not end the statement the label may be + // the body of (`if (c) l:` before the line). + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); + let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); + if self.objects.len() < self.acc.limits.nesting { + self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); + } } else { self.unbind(&a.name); } @@ -1316,9 +1494,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other // name before `=` is a variable, at the start of a statement or inside an expression. if !member_mark(h1) && !is(h1, "@") { + if !self.scopes.is_empty() && !self.declared_in_body(name.text) { + self.reassigned_later(name.text); + } self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } + if let Some((name, _)) = self.updated(t) + && !self.scopes.is_empty() + && !self.declared_in_body(name) + { + self.reassigned_later(name); + } match self.updated(t) { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). @@ -1328,6 +1515,85 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins + /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` + /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods. + fn settle_literal(&mut self, t: &Sig<'s>) { + if let Some((name, bits)) = self.closed.take() + && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.later_full + && !self.later.contains(&name) + && !self.declared.looped_full + && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) + { + self.writers.insert(name, bits); + } + } + + /// `name` may get another value when code read elsewhere runs: a function body assigns it without + /// declaring it, and the function may be called before or after any line, or it is assigned as a + /// property of `this`. Its object literal's methods are no longer known, now or later. + fn reassigned_later(&mut self, name: &str) { + self.writers.remove(name); + if !self.later.contains(name) { + if self.acc.room(self.later.len()) { + self.later.insert(name.to_string()); + } else { + self.later_full = true; + } + } + } + + /// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`], + /// and when a function body's own variable hides it, the global's methods saved for the body's + /// end are no longer known either. + pub(super) fn reassigned_global(&mut self, name: &str) { + self.reassigned_later(name); + if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) { + saved.writer = 0; + } + } + + /// Whether `name` is declared in the innermost function body (`var name`, `function + /// name`, a parameter). + fn declared_in_body(&self, name: &str) -> bool { + self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local)) + } + + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single + /// function expression directly inside its braces as the whole value of a key that names a + /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) + /// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`, + /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing + /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the + /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on + /// (`{…} && d`), see the variable as it was. + fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { + o.step(t); + } + let depth = self.depth(); + while let Some(o) = self.objects.pop_if(|o| o.depth > depth) { + if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) { + self.closed = Some((o.name, o.bits)); + } + } + let [h0, h1, h2, _] = self.h; + if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) { + return; + } + let key = match h1 { + Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), + Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), + _ => return, + }; + let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; + // A value that starts with a bracket has opened it already: the key is at the depth before it. + let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return }; + o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other })); + } + /// The variable that `t` changes to a number or a string, nothing the check follows, and whether /// the change waits for the value on the right. `name += …` and the other compound assignments /// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the @@ -1542,6 +1808,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.var_depth = None; self.conds.clear(); self.h = [None; 4]; + self.h4 = None; self.acc.steps = self.acc.steps.saturating_add(1); let d = directives::parse(t.text); let Some(name) = d.known else { diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..ca4ac99823 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; @@ -14,10 +14,41 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E /// The property a function reaches `Function` through. const CONSTRUCTOR: &str = "constructor"; +/// The statements whose parentheses the rest of the statement follows, so a line break after them +/// does not end a loop's body without braces. +const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; + /// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; +#[cfg(not(test))] +type LoopSpans = Vec<(usize, usize)>; + +#[cfg(test)] +#[derive(Default)] +pub(super) struct LoopSpans { + spans: Vec<(usize, usize)>, + reads: std::cell::Cell, +} + +#[cfg(test)] +impl std::ops::Deref for LoopSpans { + type Target = Vec<(usize, usize)>; + + fn deref(&self) -> &Self::Target { + self.reads.set(self.reads.get() + 1); + &self.spans + } +} + +#[cfg(test)] +impl std::ops::DerefMut for LoopSpans { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.spans + } +} + /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names /// they declare the function's own before any statement in it runs, and the function declarations @@ -36,6 +67,16 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The variables assigned inside a loop, its parentheses included (`name = …`), each by the + /// offset of the `{` of the function body that declares it (`None`: the global code's), with the + /// outermost loops that assign it, entries of `loop_spans`. + pub(super) looped: HashMap<(Option, &'s str), Vec>, + /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at + /// the end of the text). + pub(super) loop_spans: LoopSpans, + /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any + /// variable may be assigned in a loop. + pub(super) looped_full: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -46,14 +87,23 @@ pub(crate) struct Declared<'s> { pub(super) unsure: bool, } +#[cfg(test)] +impl Declared<'_> { + pub(crate) fn loop_span_reads(&self) -> usize { + self.loop_spans.reads.get() + } +} + /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement -/// the body is in, which goes on when the body closes. +/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it +/// so far, each with its loops ([`Declared::looped`]). struct Body<'s> { depth: usize, index: usize, names: HashSet<&'s str>, var_depth: Option, + looped: HashMap<&'s str, Vec>, } /// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in @@ -87,9 +137,46 @@ struct Declarations<'s, 'a, 'l> { untracked: Option, /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. keys: Vec, + /// The loops being read, the innermost last, up to [`crate::Limits::nesting`]. + loops: Vec, out: Declared<'s>, } +/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read, +/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object +/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether +/// the last token was that `)`. +struct Loop { + depth: usize, + stage: Stage, + block: bool, + head: bool, + after_head: bool, + /// The loop starts with `do` and has a trailing condition. + do_loop: bool, +} + +/// How far a [`Loop`] has been read. +#[derive(Clone, Copy, PartialEq)] +enum Stage { + /// The parentheses after `for` or `while`. + Head, + /// The parentheses after the `while` of a `do` loop. + DoHead, + /// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the + /// next token. + DoEnd, + /// The body's first token is next. + Start, + /// A body in braces. + Block, + /// A body that is one statement without braces. + Statement, + /// The statement of a body without braces has reached its end: the loop ends at the next token, + /// unless it is `else`, `catch` or `finally`, which go on with the statement. + Tail, +} + /// What `src` declares ([`Declared`]), read in one pass over its tokens. pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut lexer = Lexer::new(src, acc.limits.nesting); @@ -103,6 +190,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { bodies: vec![], untracked: None, keys: vec![], + loops: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -113,7 +201,15 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } + // A body the file does not close keeps its names assigned in a loop as well. + while let Some(body) = d.bodies.pop() { + d.settle_looped(body); + } let mut out = d.out; + for ids in out.looped.values_mut() { + ids.sort_unstable(); + ids.dedup(); + } out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out @@ -138,12 +234,22 @@ impl<'s> Declarations<'s, '_, '_> { if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { self.var_depth = None; } + self.loop_start(&t); if t.kind == T::Punct { self.bracket(&t); } else if t.kind == T::Ident { self.declaration(&t); } let depth = self.depth(); + self.loop_end(&t, depth); + if t.is("=") + && !self.loops.is_empty() + && !member_mark(h1) + && !is(h1, "@") + && let Some(name) = h0.filter(|s| s.kind == T::Ident) + { + self.looped(name.text); + } if let Some(after_new) = self.assign.take() { if t.word("new") && !after_new { self.assign = Some(true); @@ -167,6 +273,209 @@ impl<'s> Declarations<'s, '_, '_> { self.h = [Some(t), h0, h1]; } + /// `t`, a token before the brackets are followed past it: the body of the innermost loop starts + /// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any + /// variable may be assigned in one ([`Declared::looped_full`]). + fn loop_start(&mut self, t: &Sig<'s>) { + let [h0, h1, ..] = self.h; + let depth = self.depth(); + while let Some(l) = self.loops.last_mut() { + let after_head = std::mem::take(&mut l.after_head); + match l.stage { + Stage::Start => { + l.stage = if t.is("{") { Stage::Block } else { Stage::Statement }; + l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0); + break; + } + // A line break ends a body of one statement where the tokens on either side of it + // don't go on with it, as in [`Analyzer::token`], and it does not follow the + // parentheses of an `if` or another statement that the body goes on with. + Stage::Statement + if t.nl + && depth == l.depth + && !goes_on_after(h0) + && !goes_on_with(t) + && !after_head + && !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) => + { + l.stage = Stage::Tail; + } + Stage::Statement => { + if depth == l.depth { + if t.is("{") { + l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1)); + } else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) { + l.head = true; + } + } + break; + } + Stage::Tail if l.do_loop && t.word("while") => { + l.stage = Stage::DoHead; + return; + } + Stage::Tail if t.word("else") => { + l.stage = Stage::Statement; + break; + } + // The `catch` and `finally` of a `try` statement that is the body go on with it. + Stage::Tail if t.word("catch") || t.word("finally") => { + l.stage = Stage::Statement; + l.head = t.word("catch"); + break; + } + Stage::DoEnd if t.is(";") && depth == l.depth => break, + Stage::Tail | Stage::DoEnd => { + self.pop_loop(t.start); + // A body of one statement that is this loop ends with it. + if let Some(outer) = self.loops.last_mut() + && outer.stage == Stage::Statement + && outer.depth == depth + { + outer.stage = Stage::Tail; + } + } + _ => break, + } + } + let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) { + Stage::Head + } else if t.word("do") && !member_mark(h0) { + Stage::Start + } else { + return; + }; + if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) { + self.out.looped_full = true; + } else { + if self.loops.is_empty() { + self.out.loop_spans.push((t.start, usize::MAX)); + } + self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") }); + } + } + + /// Ends the innermost loop at offset `at`, which ends the outermost one in + /// [`Declared::loop_spans`]. + fn pop_loop(&mut self, at: usize) { + self.loops.pop(); + if self.loops.is_empty() + && let Some((_, end)) = self.out.loop_spans.last_mut() + { + *end = at; + } + } + + /// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the + /// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement + /// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a + /// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it. + fn loop_end(&mut self, t: &Sig<'s>, depth: usize) { + let mut inner = false; + while let Some(l) = self.loops.last_mut() { + let ended = depth < l.depth + || match l.stage { + Stage::Head => { + if t.is(")") && depth == l.depth { + l.stage = Stage::Start; + } + false + } + Stage::DoHead => { + if t.is(")") && depth == l.depth { + l.stage = Stage::DoEnd; + } + false + } + Stage::DoEnd => t.is(";") && depth == l.depth, + Stage::Block => { + if t.is("}") && depth == l.depth && l.do_loop { + l.stage = Stage::Tail; + false + } else { + t.is("}") && depth == l.depth + } + } + Stage::Statement => { + if depth == l.depth { + if t.is(";") || (t.is("}") && l.block) || inner { + l.stage = Stage::Tail; + } else if t.is(")") && l.head { + l.head = false; + l.after_head = true; + } + } + false + } + Stage::Start | Stage::Tail => false, + }; + if !ended { + break; + } + self.pop_loop(t.start); + inner = true; + } + } + + /// `name` is assigned in the loops being read: kept with the outermost one for the innermost + /// function body that declares it when that body closes ([`Self::settle_looped`]), or for the + /// global code. + fn looped(&mut self, name: &'s str) { + let id = self.out.loop_spans.len().saturating_sub(1); + match self.bodies.last_mut() { + Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => { + let ids = body.looped.entry(name).or_default(); + if !ids.contains(&id) { + ids.push(id); + } + } + Some(_) => self.out.looped_full = true, + None => self.keep_looped(None, name, vec![id]), + } + } + + /// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it, + /// and the others go to the body around it, or to the global code. + fn settle_looped(&mut self, body: Body<'s>) { + let start = self.out.bodies.get(body.index).map(|(at, _)| *at); + for (name, ids) in body.looped { + if body.names.contains(name) { + self.keep_looped(start, name, ids); + } else if let Some(outer) = self.bodies.last_mut() { + if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) { + let kept = outer.looped.entry(name).or_default(); + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } else { + self.out.looped_full = true; + } + } else { + self.keep_looped(None, name, ids); + } + } + } + + /// Keeps `name` of `body` as assigned in outermost loops `ids`. + fn keep_looped(&mut self, body: Option, name: &'s str, ids: Vec) { + let len = self.out.looped.len(); + match self.out.looped.get_mut(&(body, name)) { + Some(kept) => { + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } + None if self.acc.room(len) => { + self.out.looped.insert((body, name), ids); + } + None => self.out.looped_full = true, + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -234,7 +543,13 @@ impl<'s> Declarations<'s, '_, '_> { if self.bodies.len() < self.acc.limits.nesting { let index = self.out.bodies.len(); self.out.bodies.push((t.start, vec![])); - self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() }); + self.bodies.push(Body { + depth: self.depth(), + index, + names: HashSet::new(), + var_depth: self.var_depth.take(), + looped: HashMap::new(), + }); } else if self.untracked.is_none() { self.untracked = Some(self.depth()); } @@ -261,6 +576,7 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + self.settle_looped(body); } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 05c9ceaed1..ae82d4b1bc 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -85,6 +85,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } } + self.writer_use(t); match t.kind { T::Ident => self.name(t, line), T::Punct => self.punct(t, line), @@ -130,6 +131,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to + /// its own file, and the value may reach `close` through a variable or an argument. + fn save_changes(&mut self, line: Option) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } + /// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes. fn file_setter(&mut self, line: Option) { self.acc.feature(FeatureId::FileWrite, line); @@ -200,6 +208,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) { self.acc.feature(FeatureId::FilePlaces, line); } + if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) { + self.save_changes(line); + } if n == catalog::ON_DRAW { self.acc.feature(FeatureId::ScriptuiDrawing, line); } @@ -272,8 +283,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { "]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => { let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); self.setter(&name, h2, h3, line); + if name == catalog::SAVE_CHANGES + && word(h2, catalog::SAVE_OPTIONS) + && !member_mark(h3) + && !self.own_names.contains(catalog::SAVE_OPTIONS) + { + self.save_changes(line); + } } - "(" => self.call(line), + // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. + "[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)), + "(" => self.call(t, line), // `Name.prototype["+"] = …` defines an operator. "=" => { let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str())); @@ -287,17 +307,61 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just + /// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method + /// as the chain writes it (`.print()`, or `[]()` when brackets name it). + fn document_print(&self, called: &str) -> bool { + self.called_on(called).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + } + + /// Whether this `(` calls a method of the application object: `receiver`, which `before` comes + /// before, is the application object ([`Self::app_receiver`]), or the document-model member chain + /// the `(` has just set aside until its `)` is `app` followed by `called`. The chain starts at `app` + /// or at a variable that holds it, never at a property named `app` or at an `app` the script declared. + fn app_call(&self, called: &str, receiver: Option>, before: Option>) -> bool { + self.app_receiver(receiver, before) || self.called_on(called) == Some(catalog::DOM_ROOTS[0]) + } + + /// Whether the method `name`, which a string literal in brackets named, gives a document: the + /// member chain this `(` has just set aside, with `name` called on its receiver, is one of + /// [`catalog::DOM_DOCUMENTS`]. + fn gives_document(&self, name: &str) -> bool { + let named = + |receiver: &str, d: &str| d.strip_prefix(receiver).and_then(|m| m.strip_prefix('.')).and_then(|m| m.strip_suffix("()")) == Some(name); + self.called_on("[]()").is_some_and(|receiver| catalog::DOM_DOCUMENTS.iter().any(|d| named(receiver, d))) + } + + /// What the document-model member chain that this `(` has just set aside until its `)` holds before + /// `called`, when the chain ends with `called`. + fn called_on(&self, called: &str) -> Option<&str> { + let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth()); + chain.and_then(|c| c.path.strip_suffix(called)) + } + /// `(` after a name: a call. - fn call(&mut self, line: Option) { + fn call(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; - // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + // `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) { - self.acc.feature(FeatureId::FileWrite, line); - self.acc.outside(OutsideId::FilesWritten, line, None); + if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name)) + || (name == catalog::DOM_PRINT && self.document_print("[]()")) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_call("[]()", h3, self.h4) { + self.acc.feature(FeatureId::FileRead, line); + } + // `app['open'](f)` and `app.documents['index'](0)` give a document, as `app.open(f)` and + // `app.documents.index(0)` do. + if self.gives_document(&name) { + let (depth, cap) = (self.depth(), self.chain_cap()); + if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) { + c.name_call(&name, cap); + } + } return; } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; @@ -318,9 +382,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::ScriptuiDrawing, line); } else if catalog::INSTANCE_DIALOGS.contains(&n) { self.acc.feature(FeatureId::FileDialog, line); - } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { + } else if catalog::FOLDER_READS.contains(&n) + || (file && catalog::FILE_READS.contains(&n)) + || (catalog::DOM_FILE_READS.contains(&n) && self.app_call(&format!(".{n}()"), h2, h3)) + { self.acc.feature(FeatureId::FileRead, line); - } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)) + || (n == catalog::DOM_PRINT && self.document_print(".print()")) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { @@ -343,6 +413,93 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether `receiver`, which `before` comes before, is the application object: the name `app` + /// that no `.` comes before and that the script has not declared as its own. + fn app_receiver(&self, receiver: Option>, before: Option>) -> bool { + word(receiver, catalog::DOM_ROOTS[0]) && !member_mark(before) && !self.shadowed.first().copied().unwrap_or(true) + } + + /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding + /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; + /// 0 for anything else. A receiver the check does not follow may be a document. + /// At call offset `at`, a variable assigned in a loop containing that offset may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { + match receiver { + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let Some(bits) = self.writers.get(r.text).copied() else { return 0 }; + if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) { + return 0; + } + let looped = at.is_some_and(|at| { + self.declared.looped_full + || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { + let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at); + next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok()) + }) + }); + if looped { 0 } else { bits } + } + _ => 0, + } + } + + /// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`, + /// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or + /// `exportFile` is assigned: another name may hold its object, or its methods may change, so its + /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, + /// `local[k] = w`, `delete local.saveAs`). + fn writer_use(&mut self, t: &Sig<'s>) { + let [h0, h1, h2, h3] = self.h; + let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); + let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + // `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a + // function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the + // global variable of that name may get another value. + if changes { + // `this`, not a property named `this` (`holder.this.d`). + let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64)) + } else { + None + }; + if let Some(name) = global { + self.reassigned_global(&name); + } + } + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text); + let escaped = if word(h0, "delete") { + // `delete local…` + writer(Some(*t), h0) + } else if let Some(name) = writer(h0, h1) { + // `local` followed by anything but a member, its own assignment or an object key's `:`. + (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) + } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { + // `local.saveAs = …` + writer(h2, h3) + } else if is(h0, "[") { + // `local[k]` with a key that is not a string literal. + writer(h1, h2).filter(|_| t.kind != T::Str) + } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { + // `local['name' + k]`. + writer(h2, h3).filter(|_| !t.is("]")) + } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { + // `local['saveAs'] = …`, not `other.local['saveAs'] = …`. + writer(h3, self.h4) + } else { + None + }; + if let Some(name) = escaped { + self.writers.remove(name); + } + } + + /// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called. + fn defines(bits: u8, method: &str) -> bool { + catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0) + } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names @@ -365,6 +522,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if t.text.contains(catalog::ACTION_TEXT) { self.acc.feature(FeatureId::Actions, line); } + // The value written as the string `"SaveOptions.SAVECHANGES"`. + let value = unquote(t.text, 32); + if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) { + self.save_changes(line); + } let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!==")); if compares && word(h1, "typename") && is(h2, ".") { let name = unquote(t.text, self.acc.limits.echo.saturating_add(1)); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index e674d4b3f4..9fdf4d73ce 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,7 +77,42 @@ pub(crate) const REFLECT: &str = "reflect"; pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"]; +// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ +pub(crate) const DOM_FILE_READS: &[&str] = &["open"]; + +// The document method that writes the file its options' `jobOptions.file` names, on the same page. +// It counts only when a member chain that ends with one of `DOM_DOCUMENTS` calls it. +pub(crate) const DOM_PRINT: &str = "print"; + +// The member chains that give a document, whole and as the chains are written (`[]` for an index, +// `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, +// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`, +// `addDocumentNoUI`, `getByName`). `index` is not on that page; it comes from VectorCraft's own binding of +// the collection (`crates/engine/src/script/dom.rs`), which returns the document at a position or with a name. +pub(crate) const DOM_DOCUMENTS: &[&str] = &[ + "activeDocument", + "app.activeDocument", + "documents[]", + "app.documents[]", + "documents.add()", + "app.documents.add()", + "documents.addDocument()", + "app.documents.addDocument()", + "documents.addDocumentNoUI()", + "app.documents.addDocumentNoUI()", + "documents.getByName()", + "app.documents.getByName()", + "documents.index()", + "app.documents.index()", + "app.open()", +]; + +// The save option of `Document.close` that saves the document to its own file: +// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and +// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions). +pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES"; +pub(crate) const SAVE_OPTIONS: &str = "SaveOptions"; // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, @@ -202,7 +237,7 @@ features! { ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, ScriptuiWindow "scriptui.window" Dialogs, - SelectTool "selectTool" HostOnly, + SelectTool "selectTool" Dom, Socket "socket" HostOnly, UnitValue "unitValue" Language, Xml "xml" Language, diff --git a/crates/scriptcheck/src/report.rs b/crates/scriptcheck/src/report.rs index b21feb20e6..6142045a3e 100644 --- a/crates/scriptcheck/src/report.rs +++ b/crates/scriptcheck/src/report.rs @@ -342,10 +342,11 @@ impl<'l> Acc<'l> { } pub fn member(&mut self, path: &str) { - if let Some(n) = self.members.get_mut(path) { + let key = self.echoed(path); + if let Some(n) = self.members.get_mut(&*key) { *n = n.saturating_add(1); } else if self.room(self.members.len()) { - self.members.insert(path.to_string(), 1); + self.members.insert(key.into_owned(), 1); } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 44255738ea..1edd1480f6 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -537,6 +537,19 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `saveAs` and `exportFile` write the file they are given; `app.open` only reads one. +#[test] +fn save_as_and_export_file_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = app.open(f);\n", + "d.saveAs(f);\n", + "app.activeDocument.exportFile(f, ExportType.PNG24);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. #[test] fn export_variables_writes_a_file() { @@ -560,6 +573,493 @@ fn export_variables_in_brackets_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +#[test] +fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() { + for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] { + let r = report(&format!( + "var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\ + eval('local = app.activeDocument');\n{call}\n" + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}"); + let written = r.outside.iter().find(|o| o.id == "filesWritten"); + assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}"); + } +} + +/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in +/// brackets, as a string or through a variable; closing without it, and the other save options, +/// write nothing. +#[test] +fn closing_with_save_changes_writes_a_file() { + let r = report(concat!( + "app.activeDocument.close();\n", + "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.SAVECHANGES);\n", + "var how = SaveOptions['SAVECHANGES'];\n", + "documents[0].close(how);\n", + "documents[1].close('SaveOptions.SAVECHANGES');\n", + "var w = new Window('dialog'); w.close(1);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 7][..])]); +} + +#[test] +fn unrelated_save_changes_properties_and_strings_do_not_report_writes() { + let r = report(concat!( + "var a = other.SAVECHANGES;\n", + "var b = other['SAVECHANGES'];\n", + "app.activeDocument.close('SAVECHANGES');\n", + "var c = holder.SaveOptions.SAVECHANGES;\n", + "var d = holder.SaveOptions['SAVECHANGES'];\n", + "var e = 'SAVECHANGES';\n", + "var key = SaveOptions['SAVECHANGES' + suffix];\n", + "var f = SaveOptions.SAVECHANGES;\n", + "var g = SaveOptions['SAVECHANGES'];\n", + "var h = 'SaveOptions.SAVECHANGES';\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[8, 9, 10][..])]); +} + +/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file +/// too; reading the method without calling it does not. +#[test] +fn save_as_and_export_file_in_brackets_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['open'](f);\n", + "app.activeDocument[\"saveAs\"](f);\n", + "var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n", + "var n = d['saveAs'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + +/// `app.open` reads the file it is given, called by name or with its name as a string literal in +/// brackets, also through a variable that holds the application; a document has no `open` method, and +/// a property or a variable named `app` is not the application. +#[test] +fn app_open_reads_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = app.open(f);\n", + "app['open'](f);\n", + "app.activeDocument['open'](f);\n", + "x.app.open(f);\n", + "x.app['open'](f);\n", + "var a = app; a.open(f);\n", + "a['open'](f);\n", + "var b = x.app; b.open(f); b['open'](f);\n", + )); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3, 7, 8][..])); + assert!(r.outside.is_empty()); + let r = report("var app = {};\napp.open(f);\napp['open'](f);\n"); + assert!(feature(&r, "file.read").is_none()); + // A short echo limit cuts the member chains the report lists, not what the check finds. + let short = Limits { echo: 4, ..Limits::default() }; + let src = + "app.open(f);\napp['open'](f);\nvar a = app; a.open(f);\nvar d = app['open'](f); d.print(o);\napp.documents.addDocumentNoUI('P').print(o);\n"; + let r = check("t.jsx", src.as_bytes(), None, &short); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[1, 2, 3, 4][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5][..])); + assert!(!r.members.is_empty()); + assert!(r.members.iter().all(|m| m.name.chars().count() <= short.echo)); +} + +/// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or +/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI`, `getByName`, +/// `index` or `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without +/// calling it, and a `print` method of another object, do not. +#[test] +fn print_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app.activeDocument.print(o);\n", + "app.activeDocument['print'](o);\n", + "var n = app.activeDocument['print'];\n", + "var d = app.documents[0]; d.print(o);\n", + "logger.print('hello'); logger['print']('hello');\n", + "app.activeDocument.name.concat(logger.print('x'));\n", + "app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n", + "var e = app.open(new File(p)); e.print(o);\n", + "activeDocument.print(o);\n", + "documents.addDocument('Print').print(o);\n", + "app.documents.addDocument('Print', s, false).print(o);\n", + "documents.addDocumentNoUI('Print').print(o);\n", + "app.documents.addDocumentNoUI('Print').print(o);\n", + "var g = app['open'](new File(p)); g.print(o);\n", + "var h = app['activeDocument'](new File(p)); h.print(o);\n", + "app.documents.index(0).print(o);\n", + "documents.index('Print')['print'](o);\n", + "var i = app.documents.index(1); i.print(o);\n", + "app.documents['index'](0).print(o);\n", + "var j = documents['getByName']('Print'); j['print'](o);\n", + "app.documents['length'](0).print(o);\n", + )); + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); +} + +/// A string literal in brackets that names `activeDocument` or `documents` reads that property, so the +/// `print` of the document it gives writes a file; any other name in the brackets, a name that is not +/// a property's, and a computed name do not give a document. +#[test] +fn print_on_a_document_named_in_brackets_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app['activeDocument'].print(o);\n", + "app[\"documents\"][0].print(o);\n", + "var d = app['documents'][1]; d.print(o);\n", + "app['documents']['add']().print(o);\n", + "app['preferences'].print(o); app['activeDocuments'].print(o); app['documents[]'].print(o);\n", + "app['documents'].print(o); app[k].print(o); x.app['activeDocument'].print(o);\n", + )); + let lines = &[2, 3, 4, 5][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); +} + +/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write +/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one +/// assigned something else since, and for a method the literal does not define, they write the file. +#[test] +fn the_scripts_own_save_as_writes_no_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var local = {saveAs: function () {}, 'n': 1};\n", + "local.saveAs(f);\n", + "local['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + "local.exportFile(f);\n", + "other.saveAs(f);\n", + "local = app.activeDocument;\n", + "local.saveAs(f);\n", + "var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n", + "t['exportFile'](f);\n", + "t.saveAs(f);\n", + "var activeDocument = {saveAs: function () {}};\n", + "app.activeDocument['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]); +} + +/// Once the script replaces or deletes such a method, indexes the object with a computed key, or +/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key +/// whose last value in the literal is not a function expression. +#[test] +fn a_changed_or_shared_own_save_as_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", + "a.saveAs = app.activeDocument.saveAs;\n", + "b['saveAs'] = w;\n", + "delete d.saveAs;\n", + "var h = e;\n", + "use(g);\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "d.saveAs(f);\n", + "e.saveAs(f);\n", + "g['saveAs'](f);\n", + "var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n", + "m.saveAs(f);\n", + "n.saveAs(f);\n", + "var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n", + "q['saveAs'](f);\n", + "s.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..])); + // A computed key may name any variable, so every `saveAs` in the script may write, the ones + // before the computed key included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); +} + +/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`, +/// before the assignment in the text: the call writes a file. One assigned only after a loop does +/// not. +#[test] +fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}};\n", + "for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) b.saveAs(f), b = app.activeDocument;\n", + "do { c.saveAs(f); } while ((c = next()));\n", + "for (;;) { d.saveAs(f); break; }\n", + "d = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 6][..])]); + // The `else` of a body without braces is in the loop; a statement after a line break that ends + // such a body is not, and neither is a variable of the same name that a function declares. + let r = report(concat!( + "var f = new File(p);\n", + "var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n", + "while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n", + "while (n--) g.saveAs(f), n\n", + "g = app.activeDocument\n", + "function k() { var h; for (;;) h = app.activeDocument; }\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + // An object literal's `}` does not end a body without braces, a call's `)` before a line break + // does, and a literal given after the last loop that assigns its variable is the script's own. + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n", + "b.saveAs(f);\n", + "while (n--) tick()\n", + "b = app.activeDocument\n", + "for (;;) { c = app.activeDocument; }\n", + "var c = {saveAs: function () {}};\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}};\n", + "while (n--) if (n)\n", + " a.saveAs(f), a = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) { b['saveAs'](f); b = app.activeDocument; }\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..])); +} + +/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without +/// braces, are in the loop; a statement after the whole loop is not. +#[test] +fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", + "var h = {saveAs: function () {}};\n", + "while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n", + "while (i++ < 2)\n", + " if (i === 2) do e.saveAs(f); while (false);\n", + " else e = app.activeDocument;\n", + "while (n--) do g.saveAs(f); while (false);\n", + "g = app.activeDocument;\n", + "while (n--) h.saveAs(f), holder.finally\n", + "h = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..])); +} + +/// A literal after a label's line break may not run, a `this` assignment in a function whose own +/// variable hides the global one changes the global, and a property `d` of another object is not +/// the variable `d`. +#[test] +fn labels_hidden_globals_and_other_objects_keep_writes_known() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = app.activeDocument;\n", + "if (no) l:\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "var b = {saveAs: function () {}};\n", + "function change() { var b; this.b = app.activeDocument; }\n", + "change(); b.saveAs(f);\n", + "var c = {saveAs: function () {}};\n", + "function keep() { var c; c = 1; }\n", + "keep(); c.saveAs(f);\n", + "var d = {saveAs: function () {}};\n", + "holder.d['saveAs'] = 1;\n", + "d.saveAs(f);\n", + "var e = {saveAs: function () {}};\n", + "e['saveAs'] = app.activeDocument.saveAs;\n", + "e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n", + "other(); g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..])); +} + +/// Only a `var` statement directly in a function body or the global code that gives its first name +/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the +/// statement. A literal given in a branch, one the value goes on from, one given by an assignment +/// or to a later name of the statement, a call inside the literal, and a variable a function gave +/// another value keep reporting the write. +#[test] +fn only_a_whole_var_value_makes_save_as_the_scripts_own() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "function choose() { d = null; d = app.activeDocument; }\n", + "d.saveAs(f);\n", + "var e = app.activeDocument;\n", + "if (flag) var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "if (flag) { var e2 = {saveAs: function () {}}; }\n", + "e2.saveAs(f);\n", + "var g = {saveAs: function () {}} && app.activeDocument;\n", + "g.saveAs(f);\n", + "var h = app.activeDocument;\n", + "h = {saveAs: function () {}, value: h.saveAs(f)};\n", + "var k = {saveAs: function () {}, value: k.saveAs(f)};\n", + "k.saveAs(f);\n", + "var x = 1, y = {saveAs: function () {}};\n", + "y.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); +} + +#[test] +fn writer_calls_after_many_assignment_loops_have_bounded_work() { + for reinitialize in [false, true] { + let mut src = "var d = {saveAs: function () {}};\n".to_string(); + for _ in 0..512 { + src.push_str("while (n--) { d = next(); }\n"); + } + if reinitialize { + src.push_str("var d = {saveAs: function () {}};\n"); + } + src.push_str("var local = {saveAs: function () {}};\n"); + for _ in 0..2048 { + src.push_str("d.saveAs(f); local.saveAs(f);\n"); + } + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let declared = analyze::declarations(&src, &mut acc); + let before = declared.loop_span_reads(); + analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let reads = declared.loop_span_reads() - before; + if reinitialize { + assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d"); + } else { + assert_eq!(reads, 0); + } + } +} + +/// A function body read before the literal that assigns its variable without declaring it may run +/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the +/// name assigns its own variable. +#[test] +fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "function choose() { d = app.activeDocument; }\n", + "var d = {saveAs: function () {}};\n", + "choose(); d.saveAs(f);\n", + "function bump() { e++; }\n", + "var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "function own() { var g; g = app.activeDocument; }\n", + "var g = {saveAs: function () {}};\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + +#[test] +fn captured_writer_receivers_can_change_before_each_call() { + for method in ["saveAs", "exportFile"] { + for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] { + for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] { + let src = format!( + "{prefix}var d = {{{method}: function () {{}}}};\n\ + function save(f) {{ {call}; }}\n\ + d = app.activeDocument; save(f);\n{suffix}" + ); + let r = report(&src); + let line = if prefix.is_empty() { 2 } else { 3 }; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}"); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[line][..])], "{src}"); + } + } + } +} + +#[test] +fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { + let r = report(concat!( + "var f = new File(p);\n", + "function outer() {\n", + " function choose() { d = app.activeDocument; }\n", + " var d = {saveAs: function () {}};\n", + " choose(); d.saveAs(f);\n", + " function bump() { e++; }\n", + " var e = {saveAs: function () {}};\n", + " bump(); e.saveAs(f);\n", + " function own() { var g; g = app.activeDocument; }\n", + " var g = {saveAs: function () {}};\n", + " own(); g.saveAs(f);\n", + "}\n", + "outer();\n", + )); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 8][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..])); +} + +/// Assigning a property of `this`, the global object in the global code and in a function called +/// without a receiver, may give the global variable of that name another value, before or after +/// its literal. +#[test] +fn assigning_a_property_of_this_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "this.d = app.activeDocument;\n", + "d.saveAs(f);\n", + "function swap() { this['e'] = app.activeDocument; }\n", + "var e = {saveAs: function () {}};\n", + "swap(); e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "this.other = 1;\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + +/// A `saveAs` key's value is a method of the script's own only when the whole value is one function +/// expression: a value that goes on after the function's body, and a literal inside another, leave +/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body +/// leaves the outer variable as it was. +#[test] +fn a_value_that_goes_on_after_the_function_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {} && app.activeDocument.saveAs};\n", + "var b = {saveAs: function () {}(f), n: 1};\n", + "var c = {saveAs: function () {} ? x : y};\n", + "var e = {saveAs: function () {}.call};\n", + "var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n", + "var m = {o: {saveAs: function () {}}};\n", + "var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n", + "}\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "e.saveAs(f);\n", + "k.saveAs(f); k.exportFile(f);\n", + "m.saveAs(f);\n", + "q.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..])); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] @@ -1596,7 +2096,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); assert!(r.members.is_empty(), "{:?}", r.members); - assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]); + assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]); } #[test] @@ -2197,6 +2697,8 @@ fn a_file_two_branches_include_is_followed_from_the_shallower_one() { ]); let limits = Limits { include_depth: 3, ..Limits::default() }; let r = check("main.jsx", b"#include 'a.jsxinc'\n#include 'b.jsxinc'\n", Some(&mut m), &limits); + // One row per #include line: main's two, a's, b's, c's and shared's. + assert_eq!(r.includes.len(), 6, "{:?}", includes(&r)); assert!(r.includes.iter().all(|i| i.status == IncludeStatus::Checked), "{:?}", includes(&r)); assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["network"]); } diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 310b9c8e6f..08fcbbd3de 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } +# Installed memory (cgroup limits included), which sizes the element limit. +vectorcraft-render = { workspace = true } kurbo = { workspace = true } # Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e0f5540b7d..e8c84530d5 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -195,7 +195,11 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("version", "1.2").attr("baseProfile", "tiny"); } if !opts.responsive { - if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { + // Explicit SVG Options override the document unit; absence keeps its native save behavior. + if let Some(unit) = opts.units { + let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals)); + root = root.attr("width", &width).attr("height", &height); + } else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { let w_val = physical_num(unit.from_pt(rect.width())); let h_val = physical_num(unit.from_pt(rect.height())); root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}")); diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 5e7afdd55a..20261eef95 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -28,6 +28,11 @@ pub(crate) use fx::BLEND; /// expansion bombs (#3564). pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// Most elements an SVG may expand to on this machine, its memory considered (#10165). +pub fn max_elements() -> usize { + budget::max_elements() as usize +} + mod convert; mod importer; mod layers; @@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) } let xml = parse(svg)?; // Before the style cascade of `depth::height`, as `import` measures it. - budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -142,7 +147,7 @@ pub(crate) fn import_finding( let xml = parse(svg)?; // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of // each element it reads; measured again below on the text usvg reads when that differs. - let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; @@ -165,8 +170,8 @@ pub(crate) fn import_finding( // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. let spent = match &src { Cow::Borrowed(_) if !rewritten => spent, - Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, - Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?, }; let files = found.files; files.spent_by_svg(spent); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs index 2520a8932a..b7b45f03da 100644 --- a/crates/svg/src/import/budget.rs +++ b/crates/svg/src/import/budget.rs @@ -6,8 +6,9 @@ //! sheets and the `style` attribute give the element, so a long style on an element that ``s //! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more //! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after -//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or -//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than +//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`] +//! bytes of copied styles is refused here instead. //! //! The copies are counted, never made: each element's count is worked out once and added up, so a //! `` of an element costs one addition, however many elements its copy holds. References @@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError}; /// which usvg stops (its count includes a root of its own). pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; +/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a +/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare. +const ELEMENT_BYTES: u64 = 8 << 10; + +/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the +/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused +/// with an error instead of running out of memory. +pub(crate) fn max_elements() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory())) +} + +/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known). +fn elements_for(memory: Option) -> u64 { + memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64)) +} + +/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it. +fn too_many_elements() -> SvgError { + let most = max_elements(); + match vectorcraft_render::installed_memory() { + Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20), + _ => SvgError::TooLarge(MAX_SVG_ELEMENTS), + } +} + /// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it /// shows, all together: VectorCraft's own limit. pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; @@ -209,7 +236,9 @@ pub(crate) struct Cost { impl Cost { /// The most an SVG and the SVG images it shows may cost together. - pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + pub(crate) fn limits() -> Cost { + Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS } + } pub(crate) fn add(self, other: Cost) -> Cost { Cost { @@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) { let (result, tests) = measure_spending(xml, left, depth); let result = result.map_err(|past| match past { - Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS), + Past::Elements => too_many_elements(), Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize), Past::Tests => SvgError::StylesTooComplex, Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH), @@ -562,6 +591,19 @@ mod tests { assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 }); } + #[test] + fn less_memory_reads_fewer_elements_up_to_the_element_limit() { + let most = MAX_SVG_ELEMENTS as u64; + assert_eq!(elements_for(None), most, "unknown memory"); + assert_eq!(elements_for(Some(0)), most, "unknown memory"); + assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory"); + // A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165). + let small = elements_for(Some(1 << 30)); + assert!(small < 400_000, "{small}"); + assert!(elements_for(Some(512 << 20)) < small); + assert!(max_elements() <= most); + } + #[test] fn style_sheet_rules_count_where_they_match() { let groups = "".repeat(4); @@ -614,7 +656,7 @@ mod tests { let xml = roxmltree::Document::parse(&deep).unwrap(); assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); - assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); for text in [chain(5, ""), svg("")] { let xml = roxmltree::Document::parse(&text).unwrap(); let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); @@ -674,7 +716,7 @@ mod tests { fn a_selector_that_never_matches_stops_at_the_test_limit() { let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); let xml = roxmltree::Document::parse(&never).unwrap(); - assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests)); let before = super::super::css::selector_tests(); let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 676708a09d..a5e7bc3e63 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -297,3 +297,40 @@ pub(super) fn rule(r: usvg::FillRule) -> FillRule { usvg::FillRule::EvenOdd => FillRule::EvenOdd, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Clip paths are shared, so children that each name the next one multiply at every level: ten + /// children on seven levels would take 10^7 reads unbounded. The paths read stay within ten (the + /// children of one clip path) per clip path read, and the clip still has shapes. + #[test] + fn clip_paths_whose_children_fan_out_are_read_a_bounded_number_of_times() { + let mut defs = String::from(r#""#); + for n in 1..8 { + let kids = format!(r#""#, n - 1).repeat(10); + defs += &format!(r#"{kids}"#); + } + let svg = format!( + r#"{defs}"# + ); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let cp = tree + .root() + .children() + .iter() + .find_map(|c| match c { + usvg::Node::Group(g) => g.clip_path(), + _ => None, + }) + .unwrap(); + let visits = std::cell::Cell::new(0usize); + let shapes = clip_shapes(cp, Affine::IDENTITY, &|_, _| { + visits.set(visits.get() + 1); + None + }); + assert!(!shapes.is_empty()); + assert!(visits.get() <= 10 * MAX_CLIP_READS, "{} paths read", visits.get()); + } +} diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 631bed3d0c..525e900c87 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -478,7 +478,7 @@ impl Files { // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the // linked SVG files measured before it left: past it, its links aren't read, and the // selector tests it made still count. - let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left); match result { Ok(cost) => reading.measured = reading.measured.add(cost), Err(e) => { @@ -593,13 +593,13 @@ impl Files { } /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most - /// what is left of [`budget::Cost::LIMITS`]. + /// what is left of [`budget::Cost::limits()`]. pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { self.set_spent(spent); } fn spent(&self) -> budget::Cost { - self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits()) } fn set_spent(&self, spent: budget::Cost) { @@ -807,7 +807,7 @@ impl Files { // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; // past the other limits, the whole SVG is refused. let spent = self.spent(); - let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) { Ok(cost) => cost, Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), Err(e) => { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ad3e91588f..222b90b25c 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -185,6 +185,53 @@ impl Encoding { } } +/// The unit of the `width` and `height` an export writes (SVG Options → Units, off Responsive). +/// The `viewBox` stays in user units (points) whatever is chosen. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SizeUnit { + /// Legacy bare numbers, unchanged: one per document point. CSS pixels are 96 per inch; + /// choose an explicit physical unit to preserve the document's physical size. + #[default] + #[serde(rename = "px")] + Px, + #[serde(rename = "pt")] + Pt, + #[serde(rename = "mm")] + Mm, + #[serde(rename = "cm")] + Cm, + #[serde(rename = "in")] + In, +} + +impl SizeUnit { + /// This unit's size in points, and the suffix a length in it carries (`px` is written bare). + fn per_point(self) -> (f64, &'static str) { + match self { + Self::Px => (1.0, ""), + Self::Pt => (1.0, "pt"), + Self::Mm => (25.4 / 72.0, "mm"), + Self::Cm => (2.54 / 72.0, "cm"), + Self::In => (1.0 / 72.0, "in"), + } + } + + /// `points` as a length in this unit. Physical sizes use at least six decimal places and + /// six significant digits, independent of coordinate precision, so rounding does not change + /// the viewBox's rendered scale. `px` keeps [`fmt_num`]'s selected `decimals`. + pub fn length(self, points: f64, decimals: u8) -> String { + let (scale, suffix) = self.per_point(); + let v = points * scale; + let places = + if !suffix.is_empty() && v.is_finite() && v != 0.0 { decimals.max(6).max((5.0 - v.abs().log10().floor()) as u8) } else { decimals }; + format!("{}{suffix}", fmt_num(v, places)) + } +} + +fn explicit_size_unit<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + SizeUnit::deserialize(d).map(Some) +} + /// The SVG profile written (SVG Options → SVG Profile). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum Profile { @@ -231,6 +278,10 @@ pub struct ExportOptions { pub minify: bool, /// Omit `width`/`height` so the SVG scales to its container. pub responsive: bool, + /// Override the document's unit for `width` and `height` (ignored when `responsive`). + /// Absent follows the document; explicit `px` writes bare numbers. Null is invalid. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "explicit_size_unit")] + pub units: Option, /// Fonts → Convert to Outlines: text becomes paths (portable, no font needed to view it). pub outline_text: bool, /// Embed the native document (passed to [`export_full`]) in `` so VectorCraft @@ -268,6 +319,7 @@ impl Default for ExportOptions { images: ImageMode::Embed, minify: false, responsive: false, + units: None, outline_text: false, preserve_editing: false, metadata: false, @@ -363,6 +415,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} objects")] TooLarge(usize), + /// The SVG expands to more objects (the first number) than this machine's memory, or the + /// process's memory limit (the second number, in MB), has room to read (#10165). + #[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")] + TooLargeForMemory(usize, u64), /// The SVG expands to more nested SVG images than the reader takes (a guard against /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] @@ -536,7 +592,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu pub use glyph::glyph_art; pub use import::{ MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, - MAX_NODES, + MAX_NODES, max_elements, }; /// Import an SVG document reading the files it links to as `opts` says, also returning warnings. @@ -717,6 +773,22 @@ mod tests { assert_eq!(fmt_num(100.0, 0), "100"); } + #[test] + fn tiny_physical_sizes_keep_their_scale() { + for unit in [SizeUnit::Pt, SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In] { + let (scale, suffix) = unit.per_point(); + for points in [200.0, 10.0, 3.0, 0.001, 1e-14, 1e-30] { + let written = unit.length(points, 1); + let value: f64 = written.strip_suffix(suffix).unwrap().parse().unwrap(); + assert!((value / scale / points - 1.0).abs() < 1e-5, "{points}pt: {written}"); + } + } + assert_eq!(SizeUnit::In.length(0.0, 1), "0in"); + // `px` is written exactly as `fmt_num` does. + assert_eq!(SizeUnit::Px.length(3.0, 1), "3"); + assert_eq!(SizeUnit::Px.length(0.01, 1), "0"); + } + #[test] fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); diff --git a/crates/svg/tests/convolve_overflow.rs b/crates/svg/tests/convolve_overflow.rs index 4c080e1944..2971027a67 100644 --- a/crates/svg/tests/convolve_overflow.rs +++ b/crates/svg/tests/convolve_overflow.rs @@ -8,8 +8,17 @@ // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use vectorcraft_doc::NodeKind; use vectorcraft_svg::import; +/// How many paths `svg` imports as: each file here holds one filtered rectangle. +fn paths(svg: &str) -> usize { + let d = import(svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut n = 0; + d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::Path { .. }))); + n +} + /// An overflowing `order` with a `kernelMatrix` that parses (usvg `parser/filter.rs`). #[test] fn convolve_matrix_overflowing_order_with_kernel_is_refused() { @@ -44,7 +53,7 @@ fn convolve_matrix_large_but_fitting_order_still_imports() { let svg = format!( r#""# ); - assert!(import(&svg).is_ok(), "order={order} fits the u32 multiply and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} fits the u32 multiply and must keep importing"); } } @@ -56,7 +65,7 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { let svg = format!( r#""# ); - assert!(import(&svg).is_ok(), "order={order} is usvg's pass-through and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} is usvg's pass-through and must keep importing"); } } @@ -65,18 +74,18 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { #[test] fn convolve_matrix_unparseable_or_mismatched_kernel_still_imports() { let mismatched = r#""#; - assert!(import(mismatched).is_ok(), "a kernel of the wrong length is usvg's pass-through"); + assert_eq!(paths(mismatched), 1, "a kernel of the wrong length is usvg's pass-through"); let unparseable = r#""#; - assert!(import(unparseable).is_ok(), "an unparseable kernel is usvg's pass-through"); + assert_eq!(paths(unparseable), 1, "an unparseable kernel is usvg's pass-through"); } /// Sane kernels keep importing: 3×3, 2×2, and a defaulted order. #[test] fn sane_convolve_matrices_still_import() { let three = r#""#; - assert!(import(three).is_ok(), "an ordinary filter must still import"); + assert_eq!(paths(three), 1, "an ordinary filter must still import"); let two = r#""#; - assert!(import(two).is_ok(), "a small kernel must still import"); + assert_eq!(paths(two), 1, "a small kernel must still import"); let defaulted = r#""#; - assert!(import(defaulted).is_ok(), "a filter without order must still import"); + assert_eq!(paths(defaulted), 1, "a filter without order must still import"); } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..c96dd72adb 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -552,21 +552,6 @@ fn clip_path_child_with_chained_clip_path_intersects() { assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip"); } -/// Clip paths are shared, so children that each name the next one multiply at every level: ten -/// children on seven levels would take 10^7 reads unbounded. The import must still finish. -#[test] -fn clip_paths_whose_children_fan_out_still_import() { - let mut defs = String::from(r#""#); - for n in 1..8 { - let kids = format!(r#""#, n - 1).repeat(10); - defs += &format!(r#"{kids}"#); - } - let svg = format!( - r#"{defs}"# - ); - assert!(import_with_report(&svg).is_ok()); -} - #[test] fn clip_path_deep_chain_preserves_art() { let mut defs = String::from(r#""#); @@ -892,11 +877,22 @@ fn styles_that_expand_past_the_limit_are_refused() { assert_eq!(art(&d).len(), 5000); } +/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose +/// memory has room for fewer (#10165). +fn past_the_element_limit(err: &SvgError) -> bool { + let most = vectorcraft_svg::MAX_NODES.min(999_999); + match *err { + SvgError::TooLarge(n) => n == most, + SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(), + _ => false, + } +} + /// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. #[test] fn a_use_chain_past_the_elements_usvg_reads_is_refused() { let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images @@ -927,9 +923,13 @@ fn svg_images_share_the_element_limit() { assert_ne!(chain, unshown); let image = image_of("image/svg+xml", &unshown); let rect = r#""#; - assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + // One image fits, unless this machine's memory has room for fewer elements than it makes. + match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) { + Ok(_) => {} + Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"), + } let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index c8a1cfd4ed..9c1cac5890 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -226,7 +226,10 @@ fn a_use_of_a_text_passes_its_properties_on_to_the_text() { #[test] fn a_use_inside_the_text_it_shows_opens() { let d = open(r##"HI"##); - assert!(texts(&d).iter().all(|t| close(t.first_style().size, 20.0, 1e-9)), "{:?}", texts(&d)); + let t = texts(&d); + assert_eq!(t.len(), 1, "{t:?}"); + assert_eq!(t[0].plain_text(), "HI"); + assert!(close(t[0].first_style().size, 20.0, 1e-9), "{t:?}"); } /// Past 1 MiB of text built for `` elements, the rest show their text with its own properties. @@ -1232,6 +1235,7 @@ fn vertical_writing_mode_runs_down_a_path() { let b = path.bounds().unwrap(); assert!(close(b.x0, b.x1, 1e-9) && close(b.y0, 20.0, 1e-9) && b.height() > 20.0, "{b:?}"); let o = glyph_origins(t); + assert_eq!(o.len(), 4, "{o:?}"); assert!(o.windows(2).all(|w| w[1].y > w[0].y), "glyphs step down: {o:?}"); // The em box is centred on the column. let lay = layout(FontDb::global(), t); diff --git a/crates/svg/tests/it/mesh_export.rs b/crates/svg/tests/it/mesh_export.rs index 78f30f50c9..281d3b1571 100644 --- a/crates/svg/tests/it/mesh_export.rs +++ b/crates/svg/tests/it/mesh_export.rs @@ -84,6 +84,16 @@ fn a_patch_is_cut_no_finer_than_its_colour_changes() { let d = doc(2, 2, |_, c| Color::rgb8(100 + c as u8, 100 + c as u8, 100 + c as u8)); let svg = export(&d, &ExportOptions::default()); assert!(pieces(&svg) <= 4, "{} pieces", pieces(&svg)); + // Each piece takes its patch's middle color: 100.5 and 101.5 round to 101 and 102. + let mut fills: Vec<&str> = svg.split("fill=\"").skip(1).filter_map(|s| s.split('"').next()).filter(|f| f.starts_with('#')).collect(); + fills.sort_unstable(); + fills.dedup(); + assert_eq!(fills, ["#656565", "#666666"], "{svg}"); + // The left column's pieces take 101 and the right column's 102, in both rows. + let img = resvg_render(&svg); + for (x, y, want) in [(60, 60, 101), (60, 140, 101), (140, 60, 102), (140, 140, 102)] { + assert_eq!(&img.pixel(x, y)[..3], &[want; 3], "({x}, {y}) {svg}"); + } assert_looks_alike(&d, &svg, in_square, 2, 0.0); } diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index ce28085b8b..261bdb5d9f 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -6,7 +6,7 @@ use vectorcraft_doc::{ StrokeLayer, TextKind, TextObject, }; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, shapes}; -use vectorcraft_svg::{ExportOptions, ObjectIds, Styling, export, import, import_with_report}; +use vectorcraft_svg::{ExportOptions, ObjectIds, SizeUnit, Styling, export, import, import_with_report}; fn doc_with(nodes: Vec) -> Document { let mut d = Document::new(200.0, 200.0); @@ -698,6 +698,48 @@ fn options_decimals_minify_responsive_artboard() { assert!(!s.contains("id=\"Layer_1\"")); } +/// An SVG written with a physical width and height (#4462) reopens at the artboard it was written from. +#[test] +fn svg_in_physical_units_reopens_at_the_same_size() { + let mut d = Document::new(200.0, 100.0); + d.units = vectorcraft_doc::Unit::Millimeters; + let n = rect_node(&mut d, Rect::new(10.0, 10.0, 60.0, 50.0), Appearance::default_art()); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let s = export(&d, &ExportOptions { units: Some(units), ..Default::default() }); + let back = import(&s).unwrap_or_else(|e| panic!("{units:?}: {e}\n{s}")); + let r = back.artboards[0].rect; + assert!((r.width() - 200.0).abs() < 0.1 && (r.height() - 100.0).abs() < 0.1, "{units:?}: {r:?}\n{s}"); + } +} + +/// A viewer's default `meet` scaling must preserve the artwork's physical extent, not just +/// reopen an artboard with roughly the right width and height. +#[test] +fn physical_units_preserve_rendered_extent_at_low_coordinate_precision() { + for (width, height, decimals) in [(200.0, 10.0, 1), (10.0, 200.0, 1), (0.2, 0.1, 1), (0.002, 0.001, 3)] { + let mut d = Document::new(width, height); + let n = rect_node(&mut d, Rect::new(0.0, 0.0, width, height), Appearance::basic(solid("#000000"), Paint::None, 0.0)); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let svg = export(&d, &ExportOptions { units: Some(units), decimals, ..Default::default() }); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let extent = tree.root().abs_bounding_box(); + // CSS consumers render physical lengths at 96 px/in, document geometry is 72 pt/in. + for (actual, expected) in [ + (tree.size().width(), width * 96.0 / 72.0), + (tree.size().height(), height * 96.0 / 72.0), + (extent.width(), width * 96.0 / 72.0), + (extent.height(), height * 96.0 / 72.0), + ] { + assert!((f64::from(actual) / expected - 1.0).abs() < 2e-5, "{units:?}: {actual} != {expected}\n{svg}"); + } + } + } +} + #[test] fn unique_sanitized_ids() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 3e4ba8b697..b48c486446 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -56,6 +56,7 @@ fn current_color_and_context_colours_are_the_texts() { let (art, _) = glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap(); let mut strokes = vec![]; art.walk(&mut |c| strokes.push(c.appearance.stroke_paint())); + assert_eq!(strokes.len(), seen.len(), "the same art without the text's stroke: {strokes:?}"); assert!(strokes.iter().all(|p| *p == Paint::None), "no stroke without the text's: {strokes:?}"); let plain = r##""##; assert!(!glyph_art(plain.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1, "a document in its own colours"); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 1d1b4cc712..05e70265fa 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -554,7 +554,10 @@ fn symbols_inside_themselves_end() { d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(g) }); instance(&mut d, "Loop", Affine::translate((20.0, 20.0))); let svg = export(&d, &ExportOptions::default()); - assert!(import(&svg).is_ok(), "{svg}"); + // The symbol that holds itself is not written into itself; the other one still comes back. + assert!(svg.matches(") -> Self { - // No platform folders, font store or font service. - let catalog = Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false); - // A path that isn't a folder is a font file named by itself, read whatever its name (font - // services keep fonts in files without an extension); one that becomes a folder is read as one. - let (folders, files): (Vec, Vec) = font_dirs.into_iter().partition(|p| p.is_dir()); - let catalog = catalog.with_lister(Arc::new(move || files.clone())); - catalog.set_app_dirs(folders); - Self::new(catalog) + Self::new(font_dirs_catalog(font_dirs)) + } + + /// [`FontDb::with_font_dirs`] whose every scan also calls `lister` before it reads a folder, + /// for tests that hold a scan until they let it go on. + #[cfg(test)] + pub(crate) fn with_font_dirs_and_lister(font_dirs: Vec, lister: craft::font_catalog::Lister) -> Self { + Self::new(font_dirs_catalog(font_dirs).with_lister(lister)) } /// Same scan paths as [`FontDb::global`] (platform lister and font folders), for tests. @@ -418,3 +418,15 @@ impl FontDb { false } } + +/// [`FontDb::with_font_dirs`]'s catalog: it reads `font_dirs` (folders with their subfolders, and +/// font files) and no platform folders, font store or font service. +fn font_dirs_catalog(font_dirs: Vec) -> Catalog { + let catalog = Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false); + // A path that isn't a folder is a font file named by itself, read whatever its name (font + // services keep fonts in files without an extension); one that becomes a folder is read as one. + let (folders, files): (Vec, Vec) = font_dirs.into_iter().partition(|p| p.is_dir()); + let catalog = catalog.with_lister(Arc::new(move || files.clone())); + catalog.set_app_dirs(folders); + catalog +} diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index 2fef163351..9c8daf19bf 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -687,9 +687,11 @@ mod tests { #[test] fn kinds_round_trip_through_their_ids() { - for kind in GlyphCategoryKind::all() { - assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind)); - } + assert_eq!(GlyphCategoryKind::StylisticSet(3).id(), "ss03"); + assert_eq!(GlyphCategoryKind::from_id("ss03"), Some(GlyphCategoryKind::StylisticSet(3))); + assert_eq!(GlyphCategoryKind::from_id("ss3"), None); + assert_eq!(GlyphCategoryKind::from_id("stylisticAlternates"), Some(GlyphCategoryKind::StylisticAlternates)); + assert_eq!(GlyphCategoryKind::from_id("figures"), Some(GlyphCategoryKind::Figures)); assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]); assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]); assert_eq!(GlyphCategoryKind::from_id("ss21"), None); diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index f2a0f1bbfe..033e632d92 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -1696,6 +1696,7 @@ fn invert_wrap_with_an_offset_bounds_its_work_on_a_tangled_shape() { assert!(GROWN_BAND_WORK.get() <= 2 * MAX_INVERT_WRAP_WORK, "{} steps", GROWN_BAND_WORK.get()); let contour: Vec<(f64, f64)> = star.iter().map(|p| (p.x, p.y)).collect(); let spans = invert_wrap_spans(&contour, 1.0, 10.0, 90.0); + assert!(!spans.is_empty(), "the line still meets the shape"); assert!(spans.iter().all(|&(a, b)| a >= 4.0 && b <= 96.0), "{spans:?}"); let square = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; assert_spans(&invert_wrap_spans(&square, f64::NAN, 45.0, 55.0), &invert_wrap_spans(&square, 0.0, 45.0, 55.0)); diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 225e58a053..5164dd1998 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels); let mut shaped = Vec::new(); shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped); - let Some(first) = shaped.first() else { return }; + let first = shaped.first().expect("the text shapes to glyphs"); let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count(); - if first.byte != 0 || first_end < 2 || first_end >= shaped.len() { - return; - } + assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family); + assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family); // Pick a narrow width that fits glyphs before one positive-advance glyph but not that next // glyph. This ensures the old per-glyph loop would have returned inside the first cluster. let mut prefix = shaped.first().map_or(0.0, |g| g.adv); @@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { None } }); + // A face whose mark has no advance gives no width that splits the cluster. let Some(width) = width else { return }; let mut object = TextObject::point(Point::ZERO, text, style); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index deeebbd519..b61afe0d4e 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -502,6 +502,21 @@ impl RetypeIndex { /// all (ranking a glyph by proportion counts as one per contour and one more); once they are /// spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { + self.near_matches_among(shape, tolerance, None) + } + + /// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the 256 + /// of its glyphs closest to `shape` in proportion, which the glyphs of the other faces cannot + /// crowd out. Empty when the index does not hold that face. + pub fn near_matches_in(&self, shape: &BezPath, tolerance: f64, face: u32) -> Vec { + match self.faces.iter().position(|f| f.id() == face) { + Some(i) => self.near_matches_among(shape, tolerance, Some(i)), + None => vec![], + } + } + + /// [`Self::near_matches`], among the glyphs of face `only` (an index into `faces`) when given. + fn near_matches_among(&self, shape: &BezPath, tolerance: f64, only: Option) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { return vec![]; @@ -528,7 +543,7 @@ impl RetypeIndex { Err(now) => seen = now, } }; - let near = self.ranked_near(&s, &mut work); + let near = self.ranked_near(&s, only, &mut work); for (_, e) in near { if work == 0 { break; @@ -572,8 +587,8 @@ impl RetypeIndex { /// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the /// share of the length each contour has, longest first. Ranking a glyph takes one comparison /// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are - /// left out. - fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + /// left out. With `only`, the glyphs of that face (an index into `faces`) alone. + fn ranked_near(&self, s: &Signature, only: Option, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); @@ -597,6 +612,9 @@ impl RetypeIndex { let cost = s.contours as u64 + 1; let mut near: Vec<(f64, &Entry)> = vec![]; for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) { + if only.is_some_and(|f| e.face != f) { + continue; + } let Some(left) = work.checked_sub(cost) else { break }; *work = left; near.push((apart(e), e)); @@ -2106,6 +2124,33 @@ mod tests { assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len()); } + #[test] + fn near_matches_in_one_face_find_its_glyphs_however_many_faces_are_drawn_alike() { + // Source Sans 3 Regular last, after 95 copies of it under other names: every face has + // several glyphs drawn as the period, far more than the 256 near matching fits in all. + let db = FontDb::with_font_dirs(vec![]); + for i in 0..MAX_FACES - 1 { + let family = format!("Crowd {i} Sans"); + let postscript = format!("Crowd{i}Sans-Regular"); + db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let mut faces: Vec> = (0..MAX_FACES - 1).map(|i| db.face(&format!("Crowd {i} Sans"), "Regular").unwrap()).collect(); + let source = db.face("Source Sans 3", "Regular").unwrap(); + faces.push(source.clone()); + let gid = source.mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap(); + let period = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid); + let simple = simplified(&period, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + for face in [&faces[0], &source] { + let found = index.near_matches_in(&simple, 0.02, face.id()); + assert!(found.iter().all(|m| m.face.id() == face.id()), "{}", face.family); + assert!(found.iter().any(|m| m.ch == '.') && found.len() <= MAX_CANDIDATES, "{}: {} matches", face.family, found.len()); + } + // A face the index does not hold has no matches. + let other = db.face("Inter", "Regular").unwrap(); + assert!(index.near_matches_in(&simple, 0.02, other.id()).is_empty()); + } + #[test] fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { // One glyph of the face is indexed for near matching: the one closest to a simplified o, @@ -2377,12 +2422,12 @@ mod tests { let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); let s = near_signature(&shape).unwrap(); let mut all = u64::MAX; - let ranked = index.ranked_near(&s, &mut all).len(); + let ranked = index.ranked_near(&s, None, &mut all).len(); assert!(ranked >= 1, "the o is ranked"); assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three"); // Enough to rank one glyph of two contours and nothing more. let mut work = 4; - assert_eq!(index.ranked_near(&s, &mut work).len(), 1); + assert_eq!(index.ranked_near(&s, None, &mut work).len(), 1); assert_eq!(work, 1); } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 40b29331f9..47d7c1eb5d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1028,6 +1028,7 @@ fn whitespace_the_primary_font_lacks_takes_the_fallback_face() { assert!((width - 60.0).abs() < 0.01, "あ あ sets at 3 em: {:?}", l.glyphs.iter().map(|g| g.advance).collect::>()); assert_ne!(l.glyphs[1].font_id, primary.id()); let l = layout(db(), &point("a\tb", style(20.0))); + assert_eq!(l.glyphs.len(), 3, "{:?}", l.glyphs); assert!(l.glyphs.iter().all(|g| g.font_id == primary.id())); } @@ -1935,7 +1936,9 @@ fn all_supplied_craft_font_families_are_registered_without_system_fonts() { return; } let db = FontDb::with_font_dirs(vec![]); - for font in CRAFT_FONTS { + // The faces the document font database loads: the tab-title face draws document tab titles + // alone and is left out. + for font in crate::craft_fonts::document_fonts() { let face = db.face(font.family, font.style).unwrap(); assert_eq!(face.family, font.family, "{} {}", font.family, font.style); } @@ -2649,6 +2652,8 @@ fn thai_loanwords_stay_whole() { let lines: Vec<&str> = l.lines.iter().map(|ln| &text[ln.start..ln.end]).collect(); // No line ends inside the word, whatever the Thai font's widths put beside it. let word = text.find("โปรแกรม").unwrap(); + assert!(lines.len() > 1, "70 pt wraps the sentence: {lines:?}"); + assert!(lines.iter().any(|ln| ln.contains("โปรแกรม")), "one line holds the word: {lines:?}"); assert!(l.lines.iter().all(|ln| ln.end <= word || ln.end >= word + "โปรแกรม".len()), "{lines:?}"); } diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index a8f035aa6e..bf47f56d5a 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -253,10 +253,15 @@ fn paragraph_direction_is_independent_and_neutrals_do_not_force_ltr() { #[test] fn hebrew_marks_stay_with_base_clusters() { let s = "שָׁלוֹם"; - let l = text_layout(s); - for g in &l.glyphs { - assert!(s.get(g.byte..g.byte + g.len).is_some()); + if FontDb::global().face_covering('ש').is_none_or(|face| !['ל', 'ו', 'ם'].into_iter().all(|c| face.covers(c))) { + eprintln!("SKIPPED: hebrew_marks_stay_with_base_clusters; no installed font covers Hebrew shin, lamed, vav and final mem"); + return; } + let l = text_layout(s); + // Each glyph's source starts at one of the four letters, never at a point after one. + let starts: std::collections::BTreeSet = l.glyphs.iter().map(|g| g.byte).collect(); + assert_eq!(starts, [0, 6, 8, 12].into(), "{:?}", l.glyphs.iter().map(|g| (g.byte, g.len)).collect::>()); + assert_source_coverage(s, &l); assert!(l.glyphs.iter().all(|g| g.rtl)); } @@ -413,6 +418,10 @@ fn bidi_isolates_numbers_and_brackets_keep_valid_clusters() { for g in &l.glyphs { assert!(s.get(g.byte..g.byte + g.len).is_some()); } + // Every character but the isolate marks is drawn by a glyph whose source holds it. + for (i, c) in s.char_indices().filter(|&(_, c)| !matches!(c, '\u{2067}' | '\u{2069}')) { + assert!(l.glyphs.iter().any(|g| (g.byte..g.byte + g.len).contains(&i)), "{s}: {c:?} at {i} has no glyph"); + } assert!(!selection_quads(&l, 0, s.len()).is_empty()); } } @@ -432,6 +441,7 @@ fn right_aligned_wrapped_rtl_keeps_trailing_spaces_outside_content() { #[test] fn visual_arrows_cross_rtl_paragraph_boundaries() { let l = text_layout("שלום\nעולם"); + assert_eq!(l.lines.len(), 2); assert!(l.lines.iter().all(|l| l.rtl)); assert_eq!(caret_horizontal(&l, 8, false), 9); assert_eq!(caret_horizontal(&l, 9, true), 8); @@ -492,6 +502,7 @@ fn paragraph_direction_overrides_the_first_strong_character() { #[test] fn left_to_right_text_is_untouched() { let l = text_layout("Plain text, 123 (and more)."); + assert_eq!((l.glyphs.len(), l.lines.len()), ("Plain text, 123 (and more).".len(), 1)); assert!(l.glyphs.iter().all(|g| !g.rtl) && l.lines.iter().all(|l| !l.rtl)); let bytes: Vec<_> = l.glyphs.iter().map(|g| g.byte).collect(); assert!(bytes.windows(2).all(|w| w[0] < w[1])); diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 9189bc2f0b..392c1295a6 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -529,7 +529,8 @@ fn manual_kerning_moves_a_right_to_left_ligature_stop_with_the_glyph() { fn a_letter_and_its_mark_has_no_inner_stop() { let db = FontDb::with_font_dirs(vec![]); let l = layout(&db, &point("e\u{0301}", "Source Sans 3")); - assert!(l.glyphs.iter().all(|g| g.carets.is_empty()), "{:?}", l.glyphs); + assert!(!l.glyphs.is_empty()); + assert!(l.glyphs.iter().all(|g| (g.byte, g.len) == (0, 3) && g.carets.is_empty()), "{:?}", l.glyphs); } /// On a path, a click on either half of the ligature goes to its nearer stop, and the selection of diff --git a/crates/text/src/tests/path_joins.rs b/crates/text/src/tests/path_joins.rs index 1ac96e3f0f..467b107b9d 100644 --- a/crates/text/src/tests/path_joins.rs +++ b/crates/text/src/tests/path_joins.rs @@ -3,7 +3,7 @@ //! stroke, is the measure. Fonts are installed ones (none is kept in the repository): the tests //! that need an Arabic font say so and stop without one. use crate::*; -use kurbo::{Affine, BezPath, Point, Shape}; +use kurbo::{BezPath, Point, Shape}; use std::sync::Arc; use vectorcraft_doc::{CharStyle, TextKind}; @@ -20,90 +20,6 @@ fn circle(r: f64) -> vectorcraft_geom::PathData { vectorcraft_geom::PathData::from_bezpath(&kurbo::Circle::new((0.0, 0.0), r).to_path(1e-3)) } -/// Type `s` in `style` on a circle of radius `r`, the whole loop for it. -fn on_circle(s: &str, style: CharStyle, r: f64) -> TextLayout { - let mut t = TextObject::point(Point::ZERO, s, style); - t.kind = TextKind::OnPath { path: circle(r), start: 0.25, end: None }; - layout(FontDb::global(), &t) -} - -/// For each pair of neighbouring glyphs on the line (in visual order, inside a word), how far -/// apart the right edge of the left one and the left edge of the right one are, at the baseline -/// and `h` above it. -fn gaps(l: &TextLayout, text: &str, h: f64) -> Vec<(f64, f64)> { - // Visual order: the glyphs as placed, sorted along the line by where their left edge is on it. - let edges: Vec<(Point, Point, Point, Point, usize)> = l - .glyphs - .iter() - .filter(|g| text.get(g.byte..g.byte + g.len).is_some_and(|c| !c.trim().is_empty())) - .map(|g| { - let [a, b, ..] = g.xf.as_coeffs(); - let sx = a.hypot(b); - let w = g.advance / sx; - let up = h / sx; - (g.xf * Point::new(0.0, 0.0), g.xf * Point::new(w, 0.0), g.xf * Point::new(0.0, -up), g.xf * Point::new(w, -up), g.byte) - }) - .collect(); - // Which word a byte is in: the spaces before it. - let word = |b: usize| text.get(..b).map_or(0, |t| t.chars().filter(|c| c.is_whitespace()).count()); - edges.windows(2).filter(|w| word(w[0].4) == word(w[1].4)).map(|w| ((w[0].1 - w[1].0).hypot(), (w[0].3 - w[1].2).hypot())).collect() -} - -/// The largest gaps (baseline, joining height) of type `s` on a circle of radius `r` at `size`. -fn worst(face: &FontFace, s: &str, size: f64, r: f64) -> (f64, f64) { - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let l = on_circle(s, style, r); - gaps(&l, s, size * 0.25).into_iter().fold((0.0, 0.0), |(a, b), (x, y)| (f64::max(a, x), f64::max(b, y))) -} - -/// The measure, printed: joined Arabic and separate Latin on circles at three sizes. -#[test] -fn joins_on_a_circle_are_measured() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: joins_on_a_circle_are_measured; no installed font covers Arabic"); - return; - }; - eprintln!("ASSERTIONS RUN: joins_on_a_circle_are_measured; Arabic font {} {}", face.family, face.style); - for size in [12.0, 29.0, 72.0] { - for r in [60.0, 110.0, 300.0] { - let (b, j) = worst(&face, "سلسلة متصلة", size, r); - let (lb, lj) = worst(&face, "minimum", size, r); - eprintln!("size {size:>4} r {r:>5}: arabic baseline {b:.4} join {j:.4} | latin baseline {lb:.4} at {lj:.4}"); - } - } - let _ = BezPath::new(); - let _ = Affine::IDENTITY; -} - -/// Chord placement, worked out here only (not in the layout): each glyph's baseline ends on the -/// circle, the glyph turned to the chord between them. Neighbours then meet at the baseline, and `h` -/// above it they stand apart by `h` times the angle between their chords, (a_i + a_{i+1}) / 2R. -#[test] -fn chord_placement_leaves_the_join_gap_above_the_baseline() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: chord_placement_leaves_the_join_gap_above_the_baseline; no installed font covers Arabic"); - return; - }; - let (size, r) = (29.0, 110.0); - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let s = "سلسلة"; - let l = on_circle(s, style, r); - let h = size * 0.25; - let advances: Vec = l.glyphs.iter().map(|g| g.advance).filter(|a| *a > 1e-6).collect(); - let mut worst: f64 = 0.0; - for w in advances.windows(2) { - let (a, b) = (w[0], w[1]); - // The chords' directions differ by the angle between their middles on the circle. - let turn = (a + b) / (2.0 * r); - let gap = 2.0 * h * (turn * 0.5).sin(); - let predicted = h * (a + b) / (2.0 * r); - assert!((gap - predicted).abs() < 0.01, "{gap} vs {predicted}"); - worst = worst.max(gap); - } - eprintln!("chord placement at {size} pt on radius {r}: baseline gap 0, join-height gap {worst:.3}"); - assert!(worst > 0.5, "chord placement alone leaves a visible gap: {worst}"); -} - /// A circle of radius `r` run the other way (clockwise): type on it stands on the inside, its /// tops towards the centre, as Flip puts it. fn circle_reversed(r: f64) -> vectorcraft_geom::PathData { diff --git a/crates/text/src/tests/ruby.rs b/crates/text/src/tests/ruby.rs index e7a7cfc1fb..b041b81e5d 100644 --- a/crates/text/src/tests/ruby.rs +++ b/crates/text/src/tests/ruby.rs @@ -104,7 +104,7 @@ fn ruby_is_half_the_base_size_by_default_and_size_follows_the_span() { whole.ruby[0].size_percent = 100.0; let half = ruby_ink(&layout(db(), &half)); let whole = ruby_ink(&layout(db(), &whole)); - assert!(half.height() < whole.height() * 0.75, "{} vs {}", half.height(), whole.height()); + assert!((half.height() / whole.height() - 0.5).abs() < 1e-6, "{} vs {}", half.height(), whole.height()); } #[test] diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 261cc1c54c..d82ca9ae38 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -524,30 +524,25 @@ fn a_background_scan_serves_the_first_lookup() { /// for the scan of the installed fonts: a large library would hold the first frame past the /// first-frame watchdog, and the app would never show its window (#5483). Once the scan ends, the /// list has the installed fonts. -#[cfg(unix)] #[test] fn the_menu_family_list_now_does_not_wait_for_the_scan() { let dir = font_dir("held-scan"); - // A named pipe with a font's name: the scan opens it and waits there until something writes. - let pipe = dir.join("Held.ttf"); - assert!(std::process::Command::new("mkfifo").arg(&pipe).status().unwrap().success()); - let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); + // The scan calls this lister before it reads the folder, and the lister waits there until the + // test drops `release`, once the calls below have returned. A list that waited for the scan + // would then hold the installed fonts. The lister gives up after 10 s, so such a list fails + // the test instead of hanging it. Later scans find `release` dropped and don't wait. + let (release, held) = std::sync::mpsc::channel::<()>(); + let held = std::sync::Mutex::new(held); + let hold: craft::font_catalog::Lister = Arc::new(move || { + let _ = held.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + Vec::new() + }); + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs_and_lister(vec![dir], hold))); let generation = db.generation(); db.scan_in_background(); - // 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 ready = db.installed_fonts_ready(); let listed = db.menu_family_list_now(); - drop(returned); - guard.join().unwrap(); + drop(release); 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)); @@ -805,6 +800,7 @@ fn a_resource_fork_gives_up_its_font_files() { /// Office's fonts: a file with nothing in it but a resource fork holding the fonts, named /// without an extension. Only macOS keeps a resource fork in a file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn the_scan_reads_suitcase_fonts() { let dir = font_dir("suitcase"); @@ -1011,6 +1007,7 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { /// A search reads a suitcase font only when its whole resource fork fits in the 8 MB a search reads /// of one file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_search_reads_a_suitcase_font_only_within_its_share() { use crate::fontdb::file_face_names_within; @@ -1036,6 +1033,7 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { /// A suitcase font read for one search (Retype) is read no further than one byte past the limit, /// and the bytes read are counted. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); @@ -1144,6 +1142,7 @@ fn thai_falls_back_to_a_font_made_for_thai() { let l = layout(db, &TextObject::point(kurbo::Point::ZERO, "Thai ภาษาไทย", st)); let family = |g: &PositionedGlyph| db.face_by_id(g.font_id).map(|f| f.family.clone()).unwrap_or_default(); let (latin, thai_glyphs) = l.glyphs.split_at(5); + assert_eq!(thai_glyphs.len(), "ภาษาไทย".chars().count(), "a glyph for each Thai letter"); assert!(latin.iter().all(|g| family(g) == FALLBACK_FAMILY), "{:?}", latin.iter().map(family).collect::>()); let first = crate::fontdb::THAI_FAMILIES.iter().find(|f| thai_glyphs.iter().all(|g| family(g).eq_ignore_ascii_case(f))); assert!(first.is_some(), "Thai drawn in {:?}; {thai} is installed", thai_glyphs.iter().map(family).collect::>()); diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index aff68bafd4..1d452fe72f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -562,8 +562,13 @@ fn caret_up_down_keeps_column() { let (top, _) = caret_position(&l, b); let down = caret_vertical(&l, b, 1, top.x); assert_eq!(l.line_of(down), 3); + // The caret lands on the stop of line 3 nearest the column, not on a neighbor. let (t2, _) = caret_position(&l, down); - assert!((t2.x - top.x).abs() < 12.0, "{} vs {}", t2.x, top.x); + let nearest = (l.lines[3].start..=l.lines[3].end) + .filter(|&i| COPY.is_char_boundary(i) && l.line_of(i) == 3) + .map(|i| (caret_position(&l, i).0.x - top.x).abs()) + .fold(f64::INFINITY, f64::min); + assert!(((t2.x - top.x).abs() - nearest).abs() < 1e-6, "{} vs {} (nearest stop {nearest} away)", t2.x, top.x); let up = caret_vertical(&l, down, -1, top.x); assert_eq!(up, b); assert_eq!(caret_vertical(&l, b, -10, top.x), 0); @@ -1267,34 +1272,32 @@ fn hyphenation_zone_breaks_before_the_word_with_the_single_line_composer() { assert_eq!(line_texts(&every, &layout(db(), &every)), without); } -/// The default Hyphenation options keep the line breaks of hyphenated text: the copy twice over -/// at three widths, ragged and justified, with either composer. The constant is an FNV-1a hash of -/// each line's end and whether it ends with a hyphen. It changed once since: justified lines -/// follow the default Justification options (word spacing up to 133%, where the composer used -/// to stretch spaces to 150%), and the every-line composer no longer gives up on loose lines. +/// With the default Hyphenation options, ragged and justified, with either composer: "The +/// language" in a frame that holds "The lan-" breaks as "The lan-" and "guage", only the first +/// line ends with a hyphen. The 6-letter "garden" (longer than the default 5 letters) breaks the +/// same way, as "The gar-" and "den". #[test] fn default_hyphenation_options_keep_the_line_breaks() { - let mut hash: u64 = 0xcbf2_9ce4_8422_2325; - let mut mix = |v: u64| { - for b in v.to_le_bytes() { - hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); - } + let ends_with_hyphen = |l: &TextLayout| -> Vec { + l.lines.iter().map(|li| li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0)).collect() }; - for width in [150.0, 190.0, 240.0] { - for justify in [Justify::Left, Justify::JustifyLeft] { - for composer in [Composer::SingleLine, Composer::EveryLine] { - let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), justify); - t.para.hyphenate = true; - t.para.composer = composer; - let l = layout(db(), &t); - for li in &l.lines { - let hyphenated = li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0); - mix(li.end as u64 * 2 + u64::from(hyphenated)); - } - } + for justify in [Justify::Left, Justify::JustifyLeft] { + for composer in [Composer::SingleLine, Composer::EveryLine] { + let mut t = the_language("language", composer); + t.para.justify = justify; + let l = layout(db(), &t); + assert_eq!(line_texts(&t, &l), ["The lan", "guage"], "{justify:?} {composer:?}"); + assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}"); + let w = natural_width("The gar-", 12.0).max(natural_width("garden", 12.0)) + 1.0; + assert!(w < natural_width("The garden", 12.0)); + let mut t = area("The garden", style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let l = layout(db(), &t); + assert_eq!(line_texts(&t, &l), ["The gar", "den"], "{justify:?} {composer:?}"); + assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}"); } } - assert_eq!(hash, 4_188_642_633_634_327_633); } /// The longest run of consecutive lines of `l` that end with a hyphen. diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index 2d80c2ea61..790d5491c6 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -49,9 +49,10 @@ fn a_light_straight_in_front_casts_the_silhouette_behind_the_object() { for (got, want) in [(b.x0, 100.0), (b.y0, 100.0), (b.x1, 200.0), (b.y1, 200.0)] { assert!((got - want).abs() < 1e-6, "{b:?}"); } - // Every face of the box projects into the square, and the nonzero union fills it whole. + // Every face of the box projects into the square, and the nonzero union fills it whole. Each + // sample stands for 1 pt² and none lies on the square's edge, so the count is exact. let area = covered(&path, Rect::new(90.0, 90.0, 210.0, 210.0), 120); - assert!((area - 10_000.0).abs() < 300.0, "{area}"); + assert_eq!(area, 10_000.0); } #[test] @@ -208,7 +209,7 @@ fn every_effect_casts_a_shadow() { assert!(plane.path(Shadow::default()).is_some()); let mut inflate = ShadowCaster::new(); let results = inflate.inflate(&[(&path, FillRule::NonZero)], &[true], bounds, Inflate::default(), View::default()); - assert!(results.iter().all(Result::is_ok)); + assert!(results.len() == 1 && results[0].is_ok(), "one result for the one path"); assert!(inflate.path(Shadow::default()).is_some()); let mut revolve = ShadowCaster::new(); revolve.revolve(&path, FillRule::NonZero, bounds, Revolve::default()).unwrap(); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index a4db35adb0..570ea28d4d 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -880,7 +880,7 @@ fn inflate_cells_across_a_hole_edge_are_cut_to_the_shape() { let (p, r) = shape(&b); let v = View { rotation_x: -21.88, rotation_y: -23.4, rotation_z: 9.06, ..front() }; let f = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), v).unwrap(); - assert!(f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); + assert!(!f.is_empty() && f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); // Straight on, the facets still cover exactly the shape. let flat = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap(); assert!(close(area(&flat), 220.0 * 220.0 - 100.0 * 90.0, 1e-3), "{}", area(&flat)); diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index ebbe95448a..b0fb4d4717 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -77,7 +77,8 @@ fn a_plane_has_only_a_front_and_a_hollow_solid_none() { let hollow = Extrude { cap: false, ..Extrude::default() }; assert_eq!(extrude_face_map(bounds, hollow, view, PlanarFace::Front), None); let facets = extrude(&path, FillRule::NonZero, bounds, hollow, view).unwrap(); - assert!(facets.iter().all(|f| f.end.is_none())); + // A hollow extrusion still draws its sides, and none of them is an end. + assert!(!facets.is_empty() && facets.iter().all(|f| f.end.is_none())); } #[test] diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 069013c808..46cf515f08 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -181,7 +181,7 @@ fn perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object() { assert!(eyes.windows(2).all(|w| w[0] > w[1]), "{eyes:?}"); let (p, b) = cylinder(); let wide = revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 160.0, ..Default::default() }).unwrap(); - assert!(wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(!wide.is_empty() && wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); assert_eq!(wide, revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 400.0, ..Default::default() }).unwrap()); } #[test] diff --git a/crates/three-d/src/tests/classic.rs b/crates/three-d/src/tests/classic.rs index f460297453..fc0b703741 100644 --- a/crates/three-d/src/tests/classic.rs +++ b/crates/three-d/src/tests/classic.rs @@ -87,10 +87,8 @@ fn blend_steps_round_the_shading_to_that_many_levels() { } #[test] -fn surfaces_round_trip_through_their_ids() { - for surface in ClassicSurface::ALL { - assert_eq!(ClassicSurface::parse(surface.id()), Some(surface)); - } +fn surfaces_parse_from_their_ids() { + assert_eq!(ClassicSurface::parse("none"), Some(ClassicSurface::NoShading)); assert_eq!(ClassicSurface::parse("glossy"), None); assert_eq!(ClassicSurface::default(), ClassicSurface::Plastic); } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cdc7f6f7dc..7451fd0226 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -66,11 +66,12 @@ pub struct ShapeBuilderOptions { /// region as if an invisible edge closed it. When it is off, the path cuts the regions it crosses /// as a line does. pub open_filled_as_closed: bool, - /// Pick Color From Color Swatches (`pickColorFrom: "swatches"`; off: `"artwork"`): a merge + /// Pick Color From Color Swatches (`pickColorFrom: "swatches"`, on; off: `"artwork"`): a merge /// fills the new shape with the current fill, and the Left and Right arrow keys step the current /// fill through the document's color swatches. With Artwork, the shape takes the look of the /// object where the drag starts, else of the one where it ends, else of the front-most selected - /// object. + /// object. A saved `pickColorFrom` is kept, except that preferences saved by an earlier version + /// read a saved Artwork as Color Swatches once; preferences without one take Color Swatches. pub swatches: bool, /// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill /// and the swatches before and after it show as chips above the pointer while no drag is on. @@ -105,7 +106,7 @@ impl Default for ShapeBuilderOptions { fn default() -> Self { Self { open_filled_as_closed: true, - swatches: false, + swatches: true, cursor_swatch_preview: false, straight_line: false, highlight_fill: true, diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1d9431fd47..79e69f77f6 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -409,11 +409,12 @@ impl ToolContext<'_> { pub fn star_radii_label(&self, outer: f64, inner: f64) -> String { format!("R1: {}\nR2: {}", self.len(outer), self.len(inner)) } - /// The move an arrow key nudges by: General › Keyboard Increment (ten times with Shift), - /// along General › Constrain Angle's axes; `None` for other keys. + /// The move an arrow key nudges by: General › Keyboard Increment, ten times with Shift and a + /// tenth with Ctrl/Cmd ([`nudge_step`]), along General › Constrain Angle's axes; `None` for + /// other keys. pub fn arrow_nudge(&self, key: crate::ToolKey, mods: crate::Mods) -> Option { use crate::ToolKey; - let step = self.keyboard_increment * if mods.shift { 10.0 } else { 1.0 }; + let step = nudge_step(self.keyboard_increment, mods.shift, mods.cmd); let d = match key { ToolKey::Left => Point::new(-step, 0.0), ToolKey::Right => Point::new(step, 0.0), @@ -486,3 +487,15 @@ impl ToolContext<'_> { vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() } } } + +/// The arrow keys' step: the keyboard increment, ×10 with Shift (`big`) and ÷10 with Ctrl/Cmd +/// (`fine`), so Shift+Ctrl+arrow moves by one increment. Divided, not multiplied by 0.1, so a tenth +/// of a 1 pt increment is the nearest `f64` to 0.1. +pub fn nudge_step(increment: f64, big: bool, fine: bool) -> f64 { + match (big, fine) { + (true, true) => increment, + (true, false) => increment * 10.0, + (false, true) => increment / 10.0, + (false, false) => increment, + } +} diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 1e90ce72c7..8094e88209 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -899,7 +899,7 @@ fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() { assert_eq!(got, id); // The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends. let (wide, high) = (b[2] - b[0], b[3] - b[1]); - assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}"); + assert!((wide.max(high) - 10.0).abs() < 1e-6, "{b:?}"); let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0); assert!(centre.distance(at) < 15.0, "{b:?} {at:?}"); // Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°. diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index 0f654340fe..657287124c 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -17,6 +17,8 @@ pub enum Cursor { GroupSelection, /// Alt-dragging a copy with the Selection or Direct Selection tool: a double arrowhead. SelectionCopy, + /// The Selection arrow over movable artwork. + SelectionMove, Move, Crosshair, ResizeH, diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 0b19e3e4c0..5528b7cd97 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -129,11 +129,20 @@ shown_when = [ hotspot = "The arrow's tip." look = "Arrow with a small x badge (nothing to select)." +[[cursor]] +id = "SelectionMove" +group = "Selection" +shown_when = [ + "The Selection tool over a selected object or its movable source artwork, or over its visible centre point without Cmd/Ctrl held.", + "The Selection tool over artwork while Alt is held, before the copy drag begins.", +] +hotspot = "The arrow's tip." +look = "The Selection arrow with a small move badge." + [[cursor]] id = "Move" group = "Selection" shown_when = [ - "The Selection tool over a selected object, or over any object with Alt held (once an Alt-drag starts, SelectionCopy shows).", "The shape tools over a selected object's centre point (Attributes › Show Center), before a press there moves it (while the drag runs the arrow is plain, SelectionCopy with Alt, ArrowHollow while it snaps).", "Reshape over a path or while dragging.", "Inside the Free Transform and Crop Image boxes.", diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 7f2a652e1f..b63dc44d9a 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -42,35 +42,37 @@ impl Kind { } /// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height, -/// with `preview` (Use Preview Bounds on) to the outside of its strokes. +/// to the outside of its strokes. #[derive(Clone, Debug, PartialEq)] enum Target { Segment(SegmentRef), Corner { first: SegmentRef, second: SegmentRef, at: Point }, Radial { source: DimensionSource, center: Point, radius: f64 }, - Extent { node: NodeId, preview: bool }, + Extent { node: NodeId }, } -/// A path, whether its points are moved out to its strokes, and the document its outermost points -/// ([`whole_ends`]) were read from ([`whole_box_source`]). -type WholeBoxKey = (NodeId, bool, (u64, u64, usize)); +/// A path and the document its outermost points ([`whole_ends`]) were read from +/// ([`whole_box_source`]). +type WholeBoxKey = (NodeId, (u64, u64, usize)); /// The key of a path's outermost points ([`WholeBoxKey`]), with the points. type WholeBox = (WholeBoxKey, Option<[(Point, Point); 2]>); /// The document a path's box is read from, with what identifies it: while an interaction is in /// progress, the document as it began; otherwise the document `cx` shows, at its revision. -fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId, preview: bool) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { +fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { match cx.interaction_doc { - Some(began) => (began, (node, preview, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), - None => (cx.doc, (node, preview, (cx.revision.0, cx.revision.1, 0))), + Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), + None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))), } } -/// The outermost points a dimension of the whole path `node` measures: [`dimension::extents`], or -/// with `preview` [`dimension::preview_extents`], moved out to the outside of the path's strokes. -fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - if preview { dimension::preview_extents(doc, node) } else { dimension::extents(doc, node) } +/// The outermost points a dimension the tool places on the whole path `node` measures +/// ([`dimension::preview_extents`]): moved out to the outside of the path's strokes, whether Use +/// Preview Bounds is on or off. The dimension records `"preview": true`, so it measures to there +/// after later edits too. +fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId) -> Option<[(Point, Point); 2]> { + dimension::preview_extents(doc, node) } #[derive(Default)] @@ -175,7 +177,8 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { .map_or(Orientation::Aligned, |(_, orientation)| orientation) } -/// The box through a path's outermost points ([`whole_ends`]): left, top, right and bottom. +/// The box through a path's outermost points moved out to its strokes ([`whole_ends`]): left, top, +/// right and bottom. fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect { Rect::new(left.x, top.y, right.x, bottom.y) } @@ -1045,23 +1048,23 @@ impl DimensionTool { /// document changes. While an interaction is in progress they are read from the document as /// the interaction began, which each preview starts again from (as the levels in /// [`Self::preview`] are), so the previews themselves do not make the tool read the path again. - fn whole_box(&mut self, cx: &ToolContext, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - let (from, key) = whole_box_source(cx, node, preview); + fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> { + let (from, key) = whole_box_source(cx, node); if let Some((kept, ends)) = self.whole_box && kept == key { return ends; } - let ends = whole_ends(from, node, preview); + let ends = whole_ends(from, node); self.whole_box = Some((key, ends)); ends } /// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point - /// is picked, is the whole path: with Use Preview Bounds on, to the outside of its strokes. + /// is picked, is the whole path, to the outside of its strokes. fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option { let edge = pick(cx, p)?; match self.kind { - Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node, preview: cx.preview_bounds }), + Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }), Kind::Linear => Some(Target::Segment(edge)), Kind::Angular => { let (anchor, at) = anchor_near(cx, &edge, p)?; @@ -1113,8 +1116,8 @@ impl DimensionTool { let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; self.recipe(mode, *center, p, Point::ZERO, Some(source.clone())) } - Target::Extent { node, preview } => { - let source = DimensionSource::Extent { node: *node, preview: *preview }; + Target::Extent { node } => { + let source = DimensionSource::Extent { node: *node, preview: true }; let mut d = self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(source)); d.orientation = Orientation::Horizontal; d @@ -1139,7 +1142,7 @@ impl DimensionTool { } self.level_guide = None; let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) { - Some(DimensionSource::Extent { node, preview }) => Some(self.whole_box(cx, *node, *preview)), + Some(DimensionSource::Extent { node, .. }) => Some(self.whole_box(cx, *node)), _ => None, }; let Some(d) = &mut self.pending else { return vec![] }; @@ -1408,8 +1411,8 @@ impl Tool for DimensionTool { } self.hover = self.target(cx, ev.pos, ev.mods.alt); let whole = match self.hover { - Some(Target::Extent { node, preview }) => { - self.whole_box(cx, node, preview); + Some(Target::Extent { node }) => { + self.whole_box(cx, node); true } _ => false, @@ -1562,15 +1565,14 @@ impl Tool for DimensionTool { out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true }); } } - Some(Target::Extent { node, preview }) => { - // The box through the path's outermost points (with Use Preview Bounds on, out - // to its strokes): a Smart Guide, or with Smart Guides off a line in the - // tool's own color. Read again when the path changed since the pointer last - // moved. - let (from, at) = whole_box_source(cx, *node, *preview); + Some(Target::Extent { node }) => { + // The box through the path's outermost points, out to its strokes: a Smart + // Guide, or with Smart Guides off a line in the tool's own color. Read again + // when the path changed since the pointer last moved. + let (from, at) = whole_box_source(cx, *node); let b = match self.whole_box { Some((key, ends)) if key == at => ends, - _ => whole_ends(from, *node, *preview), + _ => whole_ends(from, *node), } .map(extent_box); if let Some(b) = b { @@ -2874,7 +2876,7 @@ mod tests { } } - /// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide, + /// With Alt held, hovering a path shows the box its strokes paint as a Smart Guide, /// and a click starts placing a dimension of the whole path: above or below it, its width; /// beside it, its height. A drag places it on release. Without Alt the same click picks a point. #[test] @@ -2890,7 +2892,7 @@ mod tests { }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview: false })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); // With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by // the pointer. @@ -2907,7 +2909,7 @@ mod tests { t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); assert!(t.pending.is_some() && t.points.is_empty()); let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); - assert_eq!(above["source"], json!({"kind":"extent","node":id})); + assert_eq!(above["source"], json!({"kind":"extent","node":id,"preview":true})); assert_eq!(above["orientation"], json!("horizontal")); // Past a corner, the side the pointer is farther out on decides. let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0))); @@ -2954,29 +2956,28 @@ mod tests { assert!(o.iter().any(near), "{o:?}"); } - /// With Use Preview Bounds on, the box Alt shows over a stroked path reaches the outside of its - /// stroke, and the dimension of the whole path it places measures to there, as W and H do; it - /// keeps doing so after the art changes (`"preview": true`). With the preference off, the box - /// and the dimension go through the outermost points. + /// With Use Preview Bounds on or off, the box Alt shows over a stroked path reaches the outside + /// of its stroke, and the dimension of the whole path it places measures to there; it keeps + /// doing so after the art changes (`"preview": true`). #[test] - fn with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke() { + fn an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off() { let (d, id) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(Mods { alt: true, ..Mods::default() }); let near = |a: f64, b: f64| (a - b).abs() < 1e-9; - for (preview, (left, right)) in [(true, (99.5, 200.5)), (false, (100.0, 200.0))] { + let (left, right) = (99.5, 200.5); + for preview in [true, false] { let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); let xs: Vec = t.overlays(&c).iter().filter_map(|o| if let Overlay::Line { a, .. } = o { Some(a.x) } else { None }).collect(); assert!(xs.iter().any(|x| near(*x, left)) && xs.iter().any(|x| near(*x, right)), "preview {preview}: {xs:?}"); t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0)); t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0)); let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; - let source = if preview { json!({"kind":"extent","node":id,"preview":true}) } else { json!({"kind":"extent","node":id}) }; - assert_eq!(params["source"], source); + assert_eq!(params["source"], json!({"kind":"extent","node":id,"preview":true}), "preview {preview}"); let (a, b) = (params["a"][0].as_f64().unwrap_or(f64::NAN), params["b"][0].as_f64().unwrap_or(f64::NAN)); assert!(near(a, left) && near(b, right), "preview {preview}: {a} to {b}"); } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 30cc938428..3707d4ee88 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -681,7 +681,8 @@ fn a_marquee_selects_frame_anchors_of_area_type() { assert_eq!(a[0], Action::Begin("Reshape Type Area".into())); assert_eq!(a[1], Action::Preview("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 1], [0, 2]], "dx": 20.0, "dy": 20.0}))); assert_eq!(t.pointer(&cx2, &ev(PointerKind::Up, 440.0, 360.0)), vec![Action::Commit, Action::Notify(FRAME_PICKED.into())]); - // The arrow keys nudge them by the keyboard increment, ten times that with Shift. + // The arrow keys nudge them by the keyboard increment, ten times that with Shift, a tenth with + // Ctrl/Cmd and one increment with both (#5258). let nudged = |anchors: Value, dx: f64, dy: f64| { vec![ Action::Exec("text.reshapeArea".into(), json!({"id": text.0, "anchors": anchors, "dx": dx, "dy": dy})), @@ -691,6 +692,8 @@ fn a_marquee_selects_frame_anchors_of_area_type() { assert!(t.claims_key(&cx2, ToolKey::Right) && !t.claims_key(&cx2, ToolKey::Enter)); assert_eq!(t.key(&cx2, ToolKey::Right, Mods::default()), nudged(json!([[0, 1], [0, 2]]), 1.0, 0.0)); assert_eq!(t.key(&cx2, ToolKey::Up, Mods { shift: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), 0.0, -10.0)); + assert_eq!(t.key(&cx2, ToolKey::Left, Mods { cmd: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), -0.1, 0.0)); + assert_eq!(t.key(&cx2, ToolKey::Down, Mods { shift: true, cmd: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), 0.0, 1.0)); // Any other change of the document or the selection (Deselect, then the same type selected // again) leaves the type selected whole: the arrow keys are no longer the tool's. let mut later = cx(&d, &s, &p); diff --git a/crates/tools/src/distort/arap.rs b/crates/tools/src/distort/arap.rs index 10c355544c..4740bf556a 100644 --- a/crates/tools/src/distort/arap.rs +++ b/crates/tools/src/distort/arap.rs @@ -758,11 +758,12 @@ mod tests { }; // One pin, held at 0.4 rad: the whole shape turns rigidly around it. let d = deform(&m, &[Pin { angle: Some(0.4), ..Pin::new(c, c) }]); + assert!(!m.verts.is_empty() && d.len() == m.verts.len(), "{} of {}", d.len(), m.verts.len()); let err = m.verts.iter().zip(&d).map(|(a, b)| rot(*a).distance(*b)).fold(0.0, f64::max); assert!(err < 0.05, "{err}"); // A free pin alone leaves the shape where it is. let d = deform(&m, &[Pin::new(c, c)]); - assert!(m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); + assert!(d.len() == m.verts.len() && m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); // Held ends: the turned end turns, the other end stays. let left = Point::new(10.0, 50.0); let pins = [Pin { angle: Some(0.5), ..Pin::new(left, left) }, Pin::new(Point::new(190.0, 50.0), Point::new(190.0, 50.0))]; diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 1716a4593d..53692219c1 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -337,7 +337,7 @@ impl Tool for PerspectiveSelectionTool { if !self.claims_key(cx, key) { return vec![]; } - vec![Action::Exec("perspective.nudge".into(), json!({"dx": dx, "dy": dy, "big": mods.shift, "copy": mods.alt}))] + vec![Action::Exec("perspective.nudge".into(), json!({"dx": dx, "dy": dy, "big": mods.shift, "fine": mods.cmd, "copy": mods.alt}))] } fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { // The arrows nudge a selection in perspective. diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 06ad1c1230..e4c15c4784 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -136,7 +136,9 @@ fn neighbours(sp: &SubPath, i: usize) -> [Option; 2] { /// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it /// change. A smooth anchor takes the Curvature tool's own handles ([`smooth_handles`]: along the /// circle through it and its neighbours; at an end of an open path the one [`end_handle`] into the -/// curve). The neighbours' handles on those segments, and a corner's own +/// curve), each no longer than [`fit_to_tangent`] allows against the neighbor's handle on its +/// segment, so a point dragged far out narrows toward it instead of swinging wide around that +/// circle (#6192). The neighbors' handles on those segments, and a corner's own /// handles, keep their directions, their lengths scaling with their segment's chord, so the /// segments beyond don't move and a corner without handles keeps none. /// @@ -163,7 +165,7 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool { match ends { [Some(prev), Some(next)] => { if let Some((h_in, h_out)) = smooth_handles(prev.p, q, next.p) { - (m.h_in, m.h_out) = (h_in, h_out); + (m.h_in, m.h_out) = (fit_to_tangent(q, h_in, prev.p, prev.h_out), fit_to_tangent(q, h_out, next.p, next.h_in)); } } // An end of an open path has one segment: its handle only, and a corner like the @@ -179,6 +181,48 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool { true } +/// cos 75°: [`fit_to_tangent`] shortens a handle in full up to a turn of 150°, and less toward a +/// half turn. +const FADE_HALF_TURN: f64 = 0.258_819_045_102_520_8; + +/// Handle `h` of the point `q` on its segment to `b`, whose handle there is `hb`, shortened toward +/// the handle of the circular arc tangent to both handle lines: `2/3 · (1 − tan²(θ/4))` of `q`'s +/// distance `r` to where the lines meet, `θ` the turn between them. A longer handle swings the +/// segment out past `b`'s tangent line. The shortening applies in full while the lines meet at +/// least half the chord ahead of `b` and the turn is at most 150°, and fades to none as the meeting +/// point comes back to `b` or the turn nears a half turn, so the handle changes continuously as `q` +/// moves. Where `b` is on the circle [`smooth_handles`] +/// follows, the arc is the circle's and `h` is unchanged; `h` is also unchanged when `b` has no +/// handle there or the lines are parallel. +fn fit_to_tangent(q: Point, h: Point, b: Point, hb: Point) -> Point { + let (d, t) = (h - q, hb - b); + let (ld, lt) = (d.hypot(), t.hypot()); + let w = b - q; + let chord = w.hypot(); + if !(ld > 1e-9 && lt > 1e-9 && chord > 1e-9) { + return h; + } + let (d, t) = (d / ld, t / lt); + let den = d.cross(t); + if den.abs() <= 1e-12 { + return h; + } + // q + r·d = b + s·t. + let (r, s) = (w.cross(t) / den, w.cross(d) / den); + // The curve leaves `b` along `t` and comes into `q` along −d. + let cos_half = ((1.0 - t.dot(d)) / 2.0).clamp(0.0, 1.0).sqrt(); + // A circular arc under a half turn meets its tangents at least half its chord out. Toward a + // half turn the lines meet ever further away, on one side or the other, and the shortening + // fades out. + let weight = (2.0 * s / chord).clamp(0.0, 1.0) * (cos_half / FADE_HALF_TURN).min(1.0); + let tan2 = (1.0 - cos_half) / (1.0 + cos_half); + let cap = 2.0 / 3.0 * (1.0 - tan2) * r.abs(); + if !(weight > 0.0 && cap.is_finite() && ld > cap) { + return h; + } + q + d * (ld + (cap - ld) * weight) +} + /// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape: the new anchor's /// index. On a straight segment its handles lie along it, each a third of its own part of the /// segment ([`curvature_smooth`]: a line is a circle's limit), so a drag bends the line evenly; a drag then moves it as a diff --git a/crates/tools/src/draw2/curvature/tests.rs b/crates/tools/src/draw2/curvature/tests.rs index 50ef2281d1..f59e0ed77b 100644 --- a/crates/tools/src/draw2/curvature/tests.rs +++ b/crates/tools/src/draw2/curvature/tests.rs @@ -139,6 +139,98 @@ fn moving_a_corner_without_handles_keeps_its_sides_straight() { assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0))); } +/// A circle's top point dragged far up stretches it into a shape that narrows from its sides +/// toward the point (#6192), instead of swinging out wider than the circle first. The moved point +/// stays smooth, and its segments meet the neighbors' unchanged tangents. +#[test] +fn stretching_a_circle_narrows_toward_the_dragged_point() { + let k = 100.0 * 0.552_284_749_830_793_4; + let circle = SubPath::new( + vec![ + Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)), + Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)), + Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)), + ], + true, + ); + // On the circle, the neighbors' tangents match it, and the point keeps the circle's handles. + let mut near = circle.clone(); + assert!(curvature_move(&mut near, 0, pt(0.0, -100.0))); + for (a, b) in near.anchors.iter().zip(&circle.anchors) { + assert!(a.h_in.distance(b.h_in) < 1e-6 && a.h_out.distance(b.h_out) < 1e-6, "{a:?} != {b:?}"); + } + for top in [-150.0, -250.0, -400.0, -800.0] { + let mut sp = circle.clone(); + assert!(curvature_move(&mut sp, 0, pt(0.0, top))); + let a = sp.anchors[0]; + assert_eq!(a.kind, AnchorKind::Smooth); + assert!(collinear(a.h_in - a.p, a.h_out - a.p) && (a.h_in - a.p).dot(a.h_out - a.p) < 0.0); + // Segment 0 runs from the top to the right point, segment 3 from the left point to the top. + for (seg, side) in [(0, 1.0), (3, -1.0)] { + let c = sp.segment(seg); + let mut last: Option = None; + for j in 0..=200 { + let t = j as f64 / 200.0; + let p = c.eval(if side > 0.0 { t } else { 1.0 - t }); + assert!(p.x.abs() <= 100.0 + 1e-9, "top {top}: segment {seg} swings out to x = {}", p.x); + // From the top down to the side the width only grows. + if let Some(l) = last { + assert!(p.x.abs() >= l - 1e-9, "top {top}: segment {seg} narrows again at t = {t}"); + } + last = Some(p.x.abs()); + } + } + } +} + +/// The moved point's handles change continuously while it crosses a neighbor's tangent line, while +/// the line its own handle runs along passes through the neighbor, and while the two lines turn +/// parallel. +#[test] +fn a_moved_point_s_handles_change_continuously() { + let handles = |sp: &SubPath, q: Point| -> (Vec2, Vec2) { + let mut sp = sp.clone(); + assert!(curvature_move(&mut sp, 1, q)); + (sp.anchors[1].h_in - q, sp.anchors[1].h_out - q) + }; + let near = |a: (Vec2, Vec2), b: (Vec2, Vec2)| (a.0 - b.0).hypot() < 0.05 && (a.1 - b.1).hypot() < 0.05; + // The neighbor's handle points away from the moved point: its line passes through it at y = 0. + let away = SubPath::new( + vec![ + Anchor::corner(pt(-100.0, 0.0)), + Anchor::with_handles(pt(0.0, -20.0), pt(-30.0, -20.0), pt(30.0, -20.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(200.0, 10.0), pt(0.0, -10.0)), + ], + false, + ); + assert!(near(handles(&away, pt(0.0, -0.001)), handles(&away, pt(0.0, 0.001)))); + // The neighbor's handle runs the same way as the moved point's: their lines are parallel at x = 0. + let parallel = SubPath::new( + vec![ + Anchor::corner(pt(-100.0, 0.0)), + Anchor::with_handles(pt(0.0, -50.0), pt(-30.0, -50.0), pt(30.0, -50.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(150.0, 0.0), pt(50.0, 0.0)), + ], + false, + ); + assert!(near(handles(¶llel, pt(-0.001, -50.0)), handles(¶llel, pt(0.001, -50.0)))); + // A circle's top dragged across the right point's tangent line, x = 100. + let k = 100.0 * 0.552_284_749_830_793_4; + let circle = SubPath::new( + vec![ + Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)), + Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)), + Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)), + ], + true, + ); + for y in [-150.0, -300.0] { + assert!(near(handles(&circle, pt(99.999, y)), handles(&circle, pt(100.001, y))), "y {y}"); + } +} + #[test] fn going_on_from_an_end_keeps_the_old_segments() { let before = wave(); diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index c8aa002add..41e378649c 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3752,7 +3752,8 @@ fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_durin press(&mut t, upright, 0.5, PointerKind::Drag, 150.0); near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); let released = t.stroke_json(); - assert!(released.as_array().is_some_and(|a| a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); + // One entry per press so far (the press and two drags), each of three numbers. + assert!(released.as_array().is_some_and(|a| a.len() == 3 && a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); press(&mut t, upright, 0.5, PointerKind::Up, 150.0); } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7d0c17f068..5a32145ec0 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -67,7 +67,7 @@ mod cursor; mod input; mod readout; -pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext, ordinary_isolation}; +pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext, nudge_step, ordinary_isolation}; pub use cursor::Cursor; pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey}; pub use readout::Readout; diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index c7a205a19e..9fe1fb2138 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -79,7 +79,7 @@ pub fn gradient_params(g: &GradientPaint) -> Value { v["method"] = json!(g.gradient.method.id()); } // A freeform gradient has no ends to spread past (`paint.setFill` refuses a spread for one). - if g.gradient.is_spread() { + if !g.gradient.spread.is_pad() && g.gradient.kind != vectorcraft_color::GradientKind::Freeform { v["spread"] = json!(g.gradient.spread.label().to_lowercase()); } // A gradient that pads keeps its count for later. diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 34311e9d96..f182ce3787 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -139,9 +139,7 @@ fn actions_cycle_and_name_themselves() { assert_eq!(Stroke::Line.next(), Stroke::ContinuousArc); assert_eq!(Stroke::ContinuousArc.next(), Stroke::SharpArc); assert_eq!(Stroke::SharpArc.next(), Stroke::Line); - for s in Stroke::ALL { - assert_eq!(Stroke::parse(s.name()), Some(s)); - } + assert_eq!(Stroke::parse("sharpArc"), Some(Stroke::SharpArc)); assert_eq!(Stroke::parse("arc"), None); } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 4e3f2c16f9..1d7bd558e0 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1552,7 +1552,7 @@ impl Tool for SelectionTool { // take the pointer too (on a thin box the centre lies within a handle's reach), and with // Cmd/Ctrl held the press selects the object behind instead. if near_selected && !m.cmd && hit_center(cx, p, cx.point_tol()).is_some() { - return Cursor::Move; + return Cursor::SelectionMove; } // View → Snap to Point: over an anchor a press would grab the object by, the arrow turns // hollow. @@ -1560,11 +1560,11 @@ impl Tool for SelectionTool { return Cursor::ArrowHollow; } if selected_source_hit(cx, p).is_some() { - return Cursor::Move; + return Cursor::SelectionMove; } if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) { if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt { - return Cursor::Move; + return Cursor::SelectionMove; } return Cursor::Arrow; } diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 45bc30b47e..0ebda2c719 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -17,7 +17,7 @@ fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() { let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; for x in [75.0, 125.0] { let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}"); + assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::SelectionMove, "at {x}"); let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0)); assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}"); let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0)); @@ -45,7 +45,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() { s.set([rect, ids[1]]); let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove); let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0)); assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}"); let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0)); @@ -55,7 +55,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() { d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap(); s.set([ids[1]]); let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; - assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move); + assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove); let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0)); assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}"); } @@ -1042,7 +1042,7 @@ fn hidden_box_handles_take_no_press_while_anchors_are_selected() { s.anchors.entry(id).or_default().insert((0, 1)); let c = cx(&d, &s, &p); let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::SelectionMove); let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0)); assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}"); assert!(!crate::select::bbox_handle_at(&c, top_middle)); @@ -3006,9 +3006,9 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() { let c = ToolContext { path_only: true, ..cx(&d, &s, &p) }; let centre = Point::new(150.0, 150.0); let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::SelectionMove); // Cmd/Ctrl selects the object behind, not the centre point, so the pointer says neither. - assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::Move); + assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::SelectionMove); assert!(t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)).is_empty()); let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0)); assert_eq!(a.first(), Some(&Action::Begin("Move".into())), "{a:?}"); @@ -3102,7 +3102,7 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() { assert!(hit_center(&c, centre, c.point_tol()).is_some()); let mut t = SelectionTool::default(); let cursor = t.cursor(&c, centre, Mods::default()); - assert_ne!(cursor, Cursor::Move, "the guide's cursor, not the move arrow"); + assert_ne!(cursor, Cursor::SelectionMove, "the guide's cursor, not the move arrow"); let down = t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)); let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0)); assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}"); @@ -3177,7 +3177,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() { s.set(picked.iter().copied()); let c = cx(&d, &s, &p); let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}"); + assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "{picked:?}"); let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); assert!(!is_select(&down), "{picked:?}: {down:?}"); let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0)); @@ -3218,7 +3218,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() { s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect()); let c = cx(&d, &s, &p); let mut t = SelectionTool::default(); - assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor"); + assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "every anchor"); let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); assert!(!is_select(&down), "every anchor: {down:?}"); } diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index c6211550b3..ac4355e3a2 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum(); assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance"); assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite"); - if split_width <= 0.0 { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}" - ); - return; - } + assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family); let width = prefix_width + split_width * 0.5; assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups"); @@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6"); assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme"); assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end"); - if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}" - ); - return; - } assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred"); assert_eq!( (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start), diff --git a/crates/trace/src/group.rs b/crates/trace/src/group.rs index a0e3b85020..1050166631 100644 --- a/crates/trace/src/group.rs +++ b/crates/trace/src/group.rs @@ -451,7 +451,9 @@ mod tests { let want = parents_by_pairs(&paths, 200, 200, stacked); let pairs = BOX_TESTS.with(std::cell::Cell::get); assert_eq!(found, want, "stacked {stacked}"); - assert!(want.iter().skip(1).all(Option::is_some), "stacked {stacked}: {want:?}"); + // Each disc lies inside the one below it, the smallest that holds it. + let chain: Vec> = (0..paths.len()).map(|i| i.checked_sub(1)).collect(); + assert_eq!(want, chain, "stacked {stacked}"); assert!(tests <= pairs, "stacked {stacked}: {tests} box tests, {pairs} by pairs"); } } diff --git a/crates/trace/src/logo/restore.rs b/crates/trace/src/logo/restore.rs index 984a073f64..908d98923d 100644 --- a/crates/trace/src/logo/restore.rs +++ b/crates/trace/src/logo/restore.rs @@ -189,7 +189,13 @@ mod tests { } let (r, step) = resample_closed(&pts, 0.12).expect("resample"); let s0 = smooth_closed(&r, 0.18 / step); - let _ = restore_corners(&r, &s0, step, &RestoreParams { min_turn: 30.0, ..RestoreParams::default() }); + // The bend at (20, 0) is a candidate (turn 10), and only the minimum turn decides it. + let bend = |min_turn: f64| { + let (out, forced) = restore_corners(&r, &s0, step, &RestoreParams { turn: 10.0, min_turn, ..RestoreParams::default() }); + forced.iter().map(|&i| out[i].distance(Point::new(20.0, 0.0))).fold(f64::MAX, f64::min) + }; + assert!(bend(30.0) > 1.0, "a 20 degree bend under a 30 degree minimum: {} px from a corner", bend(30.0)); + assert!(bend(10.0) < 0.1, "under a 10 degree minimum it is one: {} px off", bend(10.0)); } #[test] diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index b0c6447d8a..6882903af9 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -311,7 +311,7 @@ mod tests { assert!(keys(seam).iter().all(|k| lower.contains(k) && upper.contains(k))); assert!(seam.path.anchor_count() <= res.anchor_count()); for a in seam.path.subpaths.iter().flat_map(|sp| &sp.anchors) { - assert!((a.p.x - 10.4).abs() < 0.5, "{a:?}"); + assert!((a.p.x - 10.4).abs() < 0.05, "{a:?}"); } let ys: Vec = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect(); assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0)); diff --git a/crates/trace/src/smooth.rs b/crates/trace/src/smooth.rs index c449f4f9ae..1c1aa25a08 100644 --- a/crates/trace/src/smooth.rs +++ b/crates/trace/src/smooth.rs @@ -191,16 +191,30 @@ mod tests { #[test] fn same_bytes_for_every_pair_of_grey_levels() { // Every pixel next to every possible neighbour, one table for all of them (the picture - // tests above run the three rounds). + // tests above run the three rounds). Each pair is one row of a 2-pixel-wide image for the + // pass along rows, and one column of a 2-pixel-high image for the pass along columns, so + // one pass checks all 65,536 pairs. let weights = weight_table(); - for p in 0..=255u8 { - for q in 0..=255u8 { - // Grey, and a mixed pair, along a row (2x1) and along a column (1x2). - for src in [[p, p, p, 255, q, q, q, 255], [p, q, p ^ q, 255, q, p, q ^ 0x5a, 255]] { - assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}"); - assert_eq!(pass(&src, 1, 2, false, &weights), reference(&src, 1, 2, false), "{p} {q}"); - } + let pairs: Vec<(u8, u8)> = (0..=255u8).flat_map(|p| (0..=255u8).map(move |q| (p, q))).collect(); + let n = pairs.len(); + // The pair of pixel `i` in the output of the pass along rows (`true`) or columns. + let pair_of = |along_rows: bool, i: usize| pairs.get(if along_rows { i / 2 } else { i % n }).copied(); + let first_difference = |along_rows: bool, fast: &[u8], slow: &[u8]| { + if fast.len() != slow.len() { + return Some(format!("lengths {} and {}", fast.len(), slow.len())); } + fast.chunks(4).zip(slow.chunks(4)).position(|(a, b)| a != b).map(|i| format!("pair {:?}", pair_of(along_rows, i))) + }; + // Gray, and a mixed pair: the two pixels made from levels `p` and `q`. + type Kind = fn(u8, u8) -> [[u8; 4]; 2]; + let kinds: [Kind; 2] = [|p, q| [[p, p, p, 255], [q, q, q, 255]], |p, q| [[p, q, p ^ q, 255], [q, p, q ^ 0x5a, 255]]]; + for (k, kind) in kinds.into_iter().enumerate() { + let rows: Vec = pairs.iter().flat_map(|&(p, q)| kind(p, q).into_iter().flatten()).collect(); + let columns: Vec = (0..2).flat_map(|side| pairs.iter().flat_map(move |&(p, q)| kind(p, q)[side])).collect(); + let fast = pass(&rows, 2, n, true, &weights); + assert_eq!(first_difference(true, &fast, &reference(&rows, 2, n, true)), None, "kind {k}, along rows"); + let fast = pass(&columns, n, 2, false, &weights); + assert_eq!(first_difference(false, &fast, &reference(&columns, n, 2, false)), None, "kind {k}, along columns"); } } diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 3fd5c2000b..b834ea4b4a 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -912,11 +912,11 @@ fn snap_curves_to_lines_straightens_near_lines() { #[test] fn presets_resolve() { - assert_eq!(presets().len(), 15); - for n in PRESET_NAMES { - assert!(preset(n).is_some(), "{n}"); - } - assert!(preset("[Default]").is_some()); + // Every name resolves: `presets` leaves out a name `preset` does not know. + assert_eq!(PRESET_NAMES.len(), 15); + assert_eq!(presets().len(), PRESET_NAMES.len()); + assert_eq!(preset("[Default]"), preset("Default")); + assert_eq!(preset(" Line Art "), preset("line art")); assert_eq!(preset("16 colors").unwrap().colors, 16); assert_eq!(preset("Shades of Gray").unwrap().mode, Mode::Grayscale); assert_eq!(preset("flat logo").unwrap().mode, Mode::Logo); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 95487e91c0..fa9d95b172 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -104,8 +104,13 @@ vectorcraft-testkit = { workspace = true } vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } +vectorcraft-plugins = { workspace = true, features = ["test-steady"] } wat = { workspace = true } [build-dependencies] serde_json = { workspace = true } toml = "1" + +# The files of other crates that this crate's tests read, for CI's test selection. +[package.metadata.craft] +reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"] diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a05d713244..ea78593400 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,8 +1,7 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and -//! Sort Objects, -//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping -//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. +//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize +//! Opacity, Sort Objects and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command +//! on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. use std::borrow::Cow; @@ -27,18 +26,25 @@ const OFFSET: &str = "addon.arrange.offset"; const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const MATCH: &str = "addon.arrange.match"; +const ROWS: &str = "addon.arrange.groupRows"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const MARKS: &str = "addon.arrange.markBounds"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 7] = [ +const DIALOGS: [(&str, &str); 9] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (MATCH, "Match Objects"), + (ROWS, "Group by Row"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (MARKS, "Mark Bounds of Each"), ]; +/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights. +const MARK_LENGTHS: std::ops::RangeInclusive = 0.001..=1e6; +const WEIGHTS: std::ops::RangeInclusive = 0.01..=1000.0; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; @@ -68,8 +74,10 @@ pub fn menu() -> Vec { c("Set Size of Each…", SIZE), c("Match Objects…", MATCH), cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), + c("Group by Row…", ROWS), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Mark Bounds of Each…", MARKS), Sep, cp("Zoom to Selection", ZOOM, json!({})), ] @@ -80,8 +88,10 @@ static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None }; +static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { @@ -154,6 +164,11 @@ fn size_rows(lengths: LengthUnits) -> Vec { ] } +fn group_rows_rows() -> Vec { + let directions = [("row", "Rows"), ("column", "Columns")]; + vec![choice("direction", "Group By:", &directions, "row")] +} + fn match_rows() -> Vec { let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")]; let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")]; @@ -186,6 +201,22 @@ fn sort_rows() -> Vec { ] } +fn marks_rows(lengths: LengthUnits) -> Vec { + let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")]; + let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")]; + vec![ + choice("style", "Draw:", &styles, "corners"), + choice("bounds", "Bounds:", &bounds, "geometric"), + length("length", "Length:", 10.0, MARK_LENGTHS, lengths).enabled_when("style", "corners"), + Param::number("weight", tl!("Weight:"), 1.0, 0.25, 2).bounds(Some(*WEIGHTS.start()), Some(*WEIGHTS.end())).unit(UnitKind::Points), + Param::new("color", tl!("Color:"), ParamKind::color(Some([1.0, 0.0, 0.0]))), + ] +} + +fn marks_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&marks_rows(POINTS), fields)) +} + fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } @@ -211,6 +242,10 @@ fn size_params(fields: &DialogFields) -> Value { Value::Object(params) } +fn group_rows_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&group_rows_rows(), fields)) +} + fn match_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&match_rows(), fields)) } @@ -241,6 +276,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })), REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })), + ROWS => (group_rows_rows(), json!({ "direction": "row" })), // The key object while the selection has one, else the top object. MATCH => ( match_rows(), @@ -259,6 +295,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -277,6 +314,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))), REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), + ROWS => super::dialogs::open(app, &ROWS_SPEC, fields, |fields| dialog(ROWS, group_rows_rows()).values(Bind::bound(fields))), MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| { let chosen = fields.text("size").is_some_and(|size| size != "none") || fields.bool("rotate") == Some(true) @@ -290,6 +328,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).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()).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index d7e93c5885..6c68fa385b 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -169,6 +169,64 @@ fn stacking(panel: &Harness) -> Vec { panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() } +/// [`app`] with a third rectangle, c, in b's row and a's column; all three selected. +fn rows_app() -> (VectorcraftApp, NodeId, NodeId, NodeId) { + let (mut app, a, b) = app(); + let c = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.all", json!({})).unwrap(); + (app, a, b, c) +} + +fn parent(panel: &Harness, id: NodeId) -> Option { + panel.app().session.doc().unwrap().doc.parent_of(id) +} + +#[test] +fn real_group_by_row_keyboard_choice_reaches_the_preview_and_ok_groups_as_one_step() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + let layer = panel.app().session.doc().unwrap().doc.layers[0].id; + // Rows: b and c share one, a is alone in its own. + assert_eq!(parent(&panel, b), parent(&panel, c), "the preview groups b's row"); + assert_ne!(parent(&panel, b), Some(layer)); + assert_eq!(parent(&panel, a), Some(layer)); + panel.click_role("Group By", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.text("direction").map(str::to_owned)), Some("column".to_owned())); + // Columns: a and c share one, b is alone in its own. + assert_eq!(parent(&panel, a), parent(&panel, c), "the preview follows the keyboard choice"); + assert_ne!(parent(&panel, a), Some(layer)); + assert_eq!(parent(&panel, b), Some(layer)); + panel.click("OK"); + panel.frame(); + let group = parent(&panel, a).unwrap(); + assert_eq!(stacking(&panel), vec![b, group], "the group takes c's place, in front of b"); + assert_eq!(parent(&panel, c), Some(group)); + assert_eq!(steps(&panel.app()), n + 1, "one undo step"); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn real_group_by_row_cancel_leaves_the_objects_ungrouped() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + assert_eq!(stacking(&panel).len(), 2, "the preview groups b and c"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(stacking(&panel), vec![a, b, c]); + assert_eq!(steps(&panel.app()), n); + assert!(!panel.app().any_dialog_open()); +} + #[test] fn real_replace_edits_reach_the_preview_and_confirmed_copies() { let (app, a, b) = app(); @@ -322,3 +380,65 @@ fn zoom_to_selection_fits_the_selection_in_the_view() { assert!(!menus::enabled(&app, ZOOM)); assert!(app.run(ZOOM, json!({})).is_err()); } + +/// The objects of the first layer, from the back. +fn layer(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// The points of the first corner mark in the marks group `id`. +fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> { + let doc = &app.session.doc().unwrap().doc; + let mark = &doc.node(id).unwrap().children().unwrap()[0]; + mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() +} + +#[test] +fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "4"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("length")), Some(4.0)); + // The preview: corner marks directly above each rectangle, their legs 4 pt long. + let preview = layer(&panel.app()); + assert_eq!((preview.len(), preview[0], preview[2]), (4, a, b), "{preview:?}"); + assert_eq!(first_mark(&panel.app(), preview[1]), vec![(4.0, 0.0), (0.0, 0.0), (0.0, 4.0)]); + panel.click("OK"); + panel.frame(); + { + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer(&app), preview); + assert_eq!(steps(&app), before + 1, "one undo step"); + } + panel.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "2"); + assert_eq!(layer(&panel.app()).len(), 5, "the preview adds marks above a"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!(layer(&app), preview, "Cancel takes the preview away"); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn mark_bounds_sends_the_dialog_values_to_its_command() { + let (mut app, a, _) = app(); + click(&mut app, "Mark Bounds of Each…"); + let id = host::dialog_id(&app); + let opened = host::read(&app, id, |f| (f.text("style").map(str::to_owned), f.text("bounds").map(str::to_owned), f.number("weight"))); + assert_eq!(opened, (Some("corners".to_owned()), Some("geometric".to_owned()), Some(1.0))); + host::set(&app, id, "style", json!("rectangle")); + host::set(&app, id, "weight", json!(3)); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let marks = layer(&app); + let doc = &app.session.doc().unwrap().doc; + let rect = doc.node(marks[1]).unwrap(); + assert_eq!((marks[0], rect.name.as_deref(), rect.appearance.stroke_width()), (a, Some("Bounds"), 3.0)); + assert_eq!(rect.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0)); +} diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 6696e4b0d3..f9d86ab058 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -3,11 +3,12 @@ //! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's //! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live //! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens -//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]) and Create Swatch Legend ([`legend`]) and -//! opens the panel. +//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and +//! Randomize Fill Colors ([`random_fill`]) and opens the panel. pub mod legend; pub mod nearest; +pub mod random_fill; use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders}; use craft::menu::Node; @@ -116,6 +117,7 @@ pub fn menu() -> Vec { // Each selected object's stroke takes its own fill, or the other way (#5530). cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})), cp("Apply Stroke to Fill", "addon.color.strokeToFill", json!({})), + c("Randomize Fill Colors…", random_fill::COMMAND), Sep, sub( "Select by Color Kind", diff --git a/crates/ui-egui/src/addons/color/random_fill.rs b/crates/ui-egui/src/addons/color/random_fill.rs new file mode 100644 index 0000000000..1ed59cb694 --- /dev/null +++ b/crates/ui-egui/src/addons/color/random_fill.rs @@ -0,0 +1,91 @@ +//! Randomize Fill Colors in the interface (Object › Plug-ins › Color Effects › Randomize Fill +//! Colors…): a dialog that picks the colors (any color, tints of a global or spot swatch, or +//! grays), the swatch, the minimum and maximum and the seed, previews on the canvas and runs +//! `addon.color.randomFill` on OK. + +use std::borrow::Cow; + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::{Label, UnitKind}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::Spec; +use crate::dialogs::form; + +/// The command OK runs, and the dialog's key. +pub const COMMAND: &str = "addon.color.randomFill"; +/// The seeds the dialog offers. +const SEEDS: u64 = 1_000_000; +/// The schemes the Colors choice offers: (`scheme`, label). +const SCHEMES: [(&str, &str); 3] = [("color", "Any Color"), ("tint", "Tints of a Swatch"), ("gray", "Grays")]; + +static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +fn percent(key: &str, label: &'static str, default: f64) -> Param { + Param::number(key, tl!(label), default, 1.0, 0).bounds(Some(0.0), Some(100.0)).unit(UnitKind::Percent).enabled_when_in("scheme", ["tint", "gray"]) +} + +/// The dialog's rows; the Swatch choice offers `swatches`. +fn rows(swatches: &[String]) -> Vec { + let schemes = SCHEMES.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect(); + let swatches: Vec<(String, Label)> = swatches.iter().map(|name| (name.clone(), name.clone().into())).collect(); + let first = swatches.first().map(|(id, _)| id.clone()); + vec![ + Param::new("scheme", tl!("Colors:"), ParamKind::choice(schemes, Some("color".into()))), + Param::new("swatch", tl!("Swatch:"), ParamKind::choice(swatches, first)).enabled_when("scheme", "tint"), + percent("min", "Minimum:", 0.0), + percent("max", "Maximum:", 100.0), + Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(SEEDS as i64 - 1), 0)), + ] +} + +/// The command's params: the swatch only for tints, the minimum and maximum only for tints and grays. +fn params(fields: &DialogFields) -> Value { + let mut p = form::json_of(&rows(&[]), fields); + let scheme = fields.text("scheme").unwrap_or("color"); + if scheme != "tint" { + p.remove("swatch"); + } + if scheme == "color" { + p.remove("min"); + p.remove("max"); + } + Value::Object(p) +} + +/// Why OK is off, if it is: a minimum above the maximum, or tints with no swatch to take them from. +fn refusal(fields: &DialogFields) -> Option<&'static str> { + let scheme = fields.text("scheme").unwrap_or("color"); + if scheme == "tint" && fields.text("swatch").is_none_or(str::is_empty) { + return Some("Make a global or spot swatch first."); + } + let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); + (scheme != "color" && min > max).then_some("The minimum is above the maximum.") +} + +/// Opens the dialog on the active document: its global and spot swatches in the Swatch choice, and a new seed whenever +/// the document has changed, so running it again gives other colors while Preview and OK agree. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let st = app.session.active().ok_or("no document")?; + let swatches: Vec = st.doc.swatches_iter().filter(|w| st.doc.global_color(&w.name).is_some()).map(|w| w.name.clone()).collect(); + let mut opening = json!({ "scheme": "color", "min": 0, "max": 100, "seed": st.revision % SEEDS }); + if let (Some(first), Some(o)) = (swatches.first(), opening.as_object_mut()) { + o.insert("swatch".into(), json!(first)); + } + let rows = rows(&swatches); + let fields = form::fields_of(&rows, opening.as_object().ok_or("no params")?); + super::super::dialogs::open(app, &SPEC, fields, move |fields| { + let refused = refusal(fields); + let mut dialog = + ParamDialog::new(COMMAND, tl!("Randomize Fill Colors"), Cow::Owned(rows.clone())).previews(true).ok_enabled(refused.is_none()); + if let Some(reason) = refused { + dialog = dialog.ok_reason(tl!(reason).into()); + } + dialog.values(Bind::bound(fields)) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/color/random_fill/tests.rs b/crates/ui-egui/src/addons/color/random_fill/tests.rs new file mode 100644 index 0000000000..c75a003b63 --- /dev/null +++ b/crates/ui-egui/src/addons/color/random_fill/tests.rs @@ -0,0 +1,116 @@ +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use crate::addons::dialogs::tests::{self as host, open_item}; +use crate::tests::panel_harness::Panel as Harness; +use crate::{VectorcraftApp, menus}; + +/// An app with a window, where its dialogs open, and two filled rectangles, both selected. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(0), rect(100)); + app.run("select.all", json!({})).unwrap(); + (app, a, b) +} + +fn fill(app: &VectorcraftApp, id: NodeId) -> Paint { + app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() +} + +fn open(app: &mut VectorcraftApp) { + open_item(app, "Color Effects", "Randomize Fill Colors…"); +} + +/// 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 the_menu_item_opens_the_dialog_on_its_command() { + let (mut app, a, b) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Color Effects"] && e.label == "Randomize Fill Colors…").unwrap(); + assert_eq!(item.command.as_deref(), Some(super::COMMAND)); + open(&mut app); + let id = host::dialog_id(&app); + let opened = host::read(&app, id, |f| (f.text("scheme").map(str::to_owned), f.number("min"), f.number("max"))); + assert_eq!(opened, (Some("color".into()), Some(0.0), Some(100.0))); + // OK on the opening values: any color, each object its own. + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(matches!(fill(&app, a), Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. }), "{:?}", fill(&app, a)); + assert_ne!(fill(&app, a), fill(&app, b)); +} + +#[test] +fn typed_grays_preview_run_on_ok_and_roll_back_on_cancel() { + let (app, a, b) = app(); + let original = fill(&app, a); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + open(&mut panel.app()); + let id = host::dialog_id(&panel.app()); + host::set(&panel.app(), id, "scheme", json!("gray")); + panel.frame(); + 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")); + let undo = panel.app().session.doc().unwrap().history.undo.len(); + panel.click("OK"); + panel.frame(); + let gray = Paint::solid(Color::gray(0.8)); + { + let app = panel.app(); + assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray.clone())); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1, "one undo step"); + assert_eq!(history.undo.last().unwrap().label, "Randomize Fill Colors"); + } + // Typed values preview at once; Cancel puts the fills back. + open(&mut panel.app()); + let id = host::dialog_id(&panel.app()); + host::set(&panel.app(), id, "scheme", json!("gray")); + host::set(&panel.app(), id, "preview", json!(true)); + panel.frame(); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert_eq!(fill(&panel.app(), a), Paint::solid(Color::gray(0.25)), "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray)); + assert_ne!(fill(&app, a), original); +} + +#[test] +fn tints_need_a_swatch_and_take_the_first_one() { + let (mut app, a, _) = app(); + open(&mut app); + let id = host::dialog_id(&app); + host::set(&app, id, "scheme", json!("tint")); + assert!(!host::confirm(&app, id), "no global or spot swatch to tint"); + host::cancel(&app, id); + host::frame(&mut app); + app.run("swatch.new", json!({"name": "Process", "color": "#336699"})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + open(&mut app); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("swatch").map(str::to_owned)), Some("Ink".into()), "process swatches are not offered"); + host::set(&app, id, "scheme", json!("tint")); + host::set(&app, id, "min", json!(30)); + host::set(&app, id, "max", json!(30)); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let Paint::Solid { swatch, tint, .. } = fill(&app, a) else { panic!("not a solid fill") }; + assert_eq!((swatch.as_deref(), tint), (Some("Ink"), 0.3)); +} diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index 506327e399..faaaca43fa 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -64,10 +64,13 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } /// Apply as Filter records a step that History and Edit › Undo name as the panel names the -/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +/// adjustment: Levels, which has fields, and Desaturate, which has none, in English and German +/// (German's plain `Levels` row and its Effect menu row differ). #[test] fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { - for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let pick = |want: &str| ADJUSTMENTS.iter().position(|a| a.0 == want).expect("an adjustment"); + for i in [pick("adjust.levels"), pick("addon.color.desaturate")] { + let (id, _, fields) = &ADJUSTMENTS[i]; let mut app = app(); app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); @@ -82,7 +85,7 @@ fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { let shown = std::rc::Rc::clone(&app); let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); fixture.room(egui::vec2(320.0, 700.0)); - for lang in crate::i18n::Lang::all() { + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("de").expect("German")] { crate::i18n::set_current(lang); let step = crate::panels::history::shown(&h); fixture.settle(); diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index b177f72604..a22e907c04 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -35,10 +35,6 @@ fn rect(app: &mut VectorcraftApp, x: f64, y: f64, width: f64, height: f64) -> u6 id_of(app.run("shape.rectangle", json!({"x": x, "y": y, "width": width, "height": height})).unwrap()) } -fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 { - id_of(app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) -} - fn select(app: &mut VectorcraftApp, ids: &[u64]) { app.run("select.set", json!({ "ids": ids })).unwrap(); } @@ -224,35 +220,6 @@ fn each_addon_dialog_opens_on_its_items_values_and_runs_its_command() { assert!(b > a, "the second object lies right of the first: {a}, {b}"); }, }, - Row { - name: "common tangents", - menu: "Path Precision Tools", - label: "Common Tangents…", - command: crate::addons::pathtools::COMMON_TANGENTS, - setup: |app| { - let (a, b) = (circle(app, 60.0, 150.0, 20.0), circle(app, 220.0, 150.0, 40.0)); - select(app, &[a, b]); - }, - opens: || json!({"tangents": "all", "centerline": false}), - set: || json!({}), - check: |app, start| { - assert_eq!(nodes(app), start.node_count() + 4, "four tangent lines"); - // Each kind the list offers is one the command takes. - for (_, kind) in crate::addons::pathtools::TANGENT_KINDS { - let params = json!({"tangents": kind}); - assert!(vectorcraft_engine::check_params(crate::addons::pathtools::COMMON_TANGENTS, ¶ms).is_ok(), "{kind}"); - } - // A circle inside another: nothing changes, and a message says why. - let ids = children(start); - let inner = circle(app, 220.0, 150.0, 10.0); - select(app, &[ids[1], inner]); - let (n, count) = (steps(app), nodes(app)); - open_item(app, "Path Precision Tools", "Common Tangents…"); - answer(app, true); - assert_eq!((steps(app), nodes(app)), (n, count)); - assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); - }, - }, Row { name: "add bounding rectangle", menu: "Path Precision Tools", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..a607911e16 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -34,6 +34,7 @@ pub(crate) struct Spec { pub(crate) struct AddonDialogs { open: Option, preview: LivePreview, + preview_error: Option<(u64, String)>, /// The open Tangent Circle Tool radius dialog. pub(crate) tangent_radius: Option, } @@ -65,6 +66,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; + app.addon_dialogs.preview_error = None; let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { @@ -102,12 +104,15 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option Result = match id { pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, - pathtools::bridge::COMMAND => pathtools::bridge::open, + pathtools::COMMON_TANGENTS => pathtools::tangents::open, + pathtools::tangents::BRIDGE => pathtools::tangents::open_connected, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, color::legend::COMMAND => color::legend::open, color::nearest::COMMAND => color::nearest::open, + color::random_fill::COMMAND => color::random_fill::open, select::COMMAND => select::open, + select::points_only::COMMAND => select::points_only::open, _ => return super::arrange::open(app, id), }; Some(open(app)) @@ -132,6 +137,7 @@ fn pump_commit(app: &mut VectorcraftApp) { if !on_document { // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. app.addon_dialogs.preview = LivePreview::default(); + app.addon_dialogs.preview_error = None; } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if on_document && let Some((previewing, params)) = &live { @@ -139,6 +145,13 @@ fn pump_commit(app: &mut VectorcraftApp) { let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; + if spec.command == super::select::points_only::COMMAND { + match &answer { + Some(Err(_)) => app.addon_dialogs.preview_error = Some((app.ui.status_sets, app.ui.status.clone())), + Some(Ok(_)) => clear_preview_error(app), + None => {} + } + } if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { if let Some(d) = h.get_mut_by_id::(id) { @@ -156,18 +169,40 @@ fn pump_commit(app: &mut VectorcraftApp) { app.status("The document was reverted. Reopen this dialog to continue."); } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); - } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { - app.status(error); + } else { + let params = (spec.params)(&result.fields); + let answer = if spec.command == super::select::points_only::COMMAND { + preview.commit_selection(app, spec.command, params) + } else { + preview.commit(app, spec.command, params) + }; + if let Err(error) = answer { + app.status(error); + } else if spec.command == super::select::points_only::COMMAND { + clear_preview_error(app); + } } + app.addon_dialogs.preview_error = None; } Some(None) => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None if live.is_none() => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None => {} } } + +fn clear_preview_error(app: &mut VectorcraftApp) { + if let Some((sets, error)) = app.addon_dialogs.preview_error.take() + && app.ui.status_sets == sets + && app.ui.status == error + { + app.ui.status.clear(); + } +} diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 679a2e2e34..dc2372552e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -87,6 +87,13 @@ fn select_two_rects(app: &mut VectorcraftApp) { app.run("select.all", json!({})).unwrap(); } +/// Two filled rectangles, both selected. +fn two_rects_filled() -> VectorcraftApp { + let mut app = two_rects(); + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + app +} + fn two_drawings() -> VectorcraftApp { let mut app = two_rects(); app.run("file.new", json!({"width": 700, "height": 500})).unwrap(); @@ -176,10 +183,10 @@ fn rows() -> Vec { }, Row { group: "Path Precision Tools", - label: "Smooth Bridge…", + label: "Common Tangents…", setup: two_circles, refused: Vec::new, - values: || vec![("keepOriginals", json!(true))], + values: || vec![("tangents", json!("external")), ("sides", json!("curved")), ("keepOriginals", json!(true))], check: |app| assert_eq!(count(app), 3, "the circles and the outline above them"), }, Row { @@ -222,6 +229,20 @@ fn rows() -> Vec { assert!(label.contains("#123456") && label.contains("C="), "{label}"); }, }, + Row { + group: "Color Effects", + label: "Randomize Fill Colors…", + setup: two_rects_filled, + refused: || vec![("scheme", json!("gray")), ("min", json!(80)), ("max", json!(20))], + values: || vec![("min", json!(40)), ("max", json!(60))], + check: |app| { + for i in 0..2 { + let fill = app.session.doc().unwrap().doc.layers[0].children().unwrap()[i].appearance.fill_paint(); + let Some(vectorcraft_color::Color::Gray { k }) = fill.color() else { panic!("not a gray: {fill:?}") }; + assert!((0.4..=0.6).contains(&k), "{k}"); + } + }, + }, ] } diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 154972dec7..3239ca6f00 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() { assert!(closed(&app), "it runs at once"); assert_eq!(steps(&app), n + 1, "one undo step"); // The defaults (tolerance and softness 10): the white goes, the near-white ring fades. - let [corner, ring, block] = alphas(&app); - assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); + assert_eq!(alphas(&app), [0, 95, 255]); } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 324f907615..2cb01c3e29 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Common Tangents… (the tangent lines, or circles connected along them, [`tangents`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog @@ -8,7 +8,6 @@ //! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its //! opening value: an anchor edit is one undo step that the cancel takes back. -pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -16,6 +15,7 @@ pub mod shape; pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; +pub mod tangents; use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; @@ -45,7 +45,7 @@ use crate::{VectorcraftApp, fields}; pub const ID: &str = "anchorInspector"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; -/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +/// Common Tangents' command, whose menu item opens its dialog ([`tangents`]). pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; @@ -143,10 +143,9 @@ pub fn menu() -> Vec { cp("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), c("Divide into Dashes…", dashes::COMMAND), cp("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), - c("Smooth Bridge…", bridge::COMMAND), cp("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), c("Tangent Circle…", tangent_circle::COMMAND), - cp("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), + c("Common Tangents…", COMMON_TANGENTS), cp("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), cp("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), cp("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs deleted file mode 100644 index 76b3627f76..0000000000 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ /dev/null @@ -1,183 +0,0 @@ -//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two -//! circles selected; Keep Originals), which previews on the canvas and runs -//! `addon.pathtools.bridge` on OK. - -use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::UnitKind; -use serde_json::{Value, json}; - -use crate::VectorcraftApp; -use crate::addons::dialogs::{self, Spec}; -use crate::canvas::rulers::general_lengths; - -/// The command. -pub const COMMAND: &str = "addon.pathtools.bridge"; -/// The radius the command takes (%), and its default. -const RADII: std::ops::RangeInclusive = 1.0..=1000.0; -const RADIUS: f64 = 100.0; -/// The gap the command takes (pt), and the dialog's first one. -const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; -const GAP: f64 = 4.0; -/// The reach the command takes (pt), and its default. -const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; -const REACH: f64 = 10.0; - -/// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; - -/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. -fn params(fields: &DialogFields) -> Value { - let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); - if fields.bool("constantGap").unwrap_or(false) { - json!({ "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) - } else { - json!({ "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) - } -} - -/// Opens Smooth Bridge's dialog on the command's defaults. -pub(crate) fn open(app: &mut VectorcraftApp) -> Result { - // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview - // replaces the selection with its result. - let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true); - let fields = DialogFields::from_pairs([ - ("radius", FieldValue::Number(RADIUS)), - ("constantGap", FieldValue::Bool(false)), - ("gap", FieldValue::Number(GAP)), - ("reach", FieldValue::Number(REACH)), - ("keepOriginals", FieldValue::Bool(false)), - ("many", FieldValue::Bool(many)), - ]); - let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |fields| { - let rows = vec![ - Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), - Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) - .length(lengths) - .bounds(Some(*GAPS.start()), Some(*GAPS.end())) - .visible_when("constantGap", FieldValue::Bool(true)), - Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) - .unit(UnitKind::Percent) - .bounds(Some(*RADII.start()), Some(*RADII.end())) - .visible_when("constantGap", FieldValue::Bool(false)), - Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) - .length(lengths) - .bounds(Some(*REACHES.start()), Some(*REACHES.end())) - .enabled_when("many", FieldValue::Bool(true)), - Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), - ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) - }) -} - -#[cfg(test)] -mod tests { - use serde_json::{Value, json}; - use vectorcraft_engine::Session; - - use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; - use crate::{VectorcraftApp, menus}; - - fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { - app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() - } - - fn bridge_app(xs: &[f64]) -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({"ids": ids})).unwrap(); - app - } - - fn geometry(app: &VectorcraftApp) -> Vec { - app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() - } - - fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { - panel.click(label); - panel.key(egui::Key::A, egui::Modifiers::COMMAND); - panel.type_text(text); - panel.key(egui::Key::Tab, egui::Modifiers::NONE); - panel.frame(); - } - - #[test] - fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); - panel.click("Keep Originals"); - type_number(&mut panel, "Radius", "150"); - let id = dialog_id(&panel.app()); - assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); - - panel.click("Constant Gap"); - type_number(&mut panel, "Gap", "6"); - let params = read(&panel.app(), id, super::params); - assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - let preview = geometry(&panel.app()); - assert_eq!(preview, geometry(&expected)); - panel.click("OK"); - panel.frame(); - assert_eq!(geometry(&panel.app()), preview); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); - assert!(!panel.app().any_dialog_open()); - } - - #[test] - fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); - let original = geometry(&panel.app()); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(panel.enabled("Reach")); - type_number(&mut panel, "Reach", "5"); - let id = dialog_id(&panel.app()); - let params = read(&panel.app(), id, super::params); - assert_eq!(params["reach"], 5.0); - let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - panel.click("Cancel"); - panel.frame(); - assert_eq!(geometry(&panel.app()), original); - } - - #[test] - fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - // Three circles 4 apart in a row and one far off. - let ids: Vec = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({ "ids": ids })).unwrap(); - menus::invoke(&mut app, super::COMMAND, Value::Null); - let dialog = dialog_id(&app); - set(&app, dialog, "constantGap", json!(true)); - // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the - // four circles the command still bridges. - frame(&mut app); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); - let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); - assert_eq!(many, Some(true), "Reach available for four circles"); - assert_eq!(params, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); - assert!(confirm(&app, dialog), "OK is on"); - frame(&mut app); - let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); - assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); - } -} diff --git a/crates/ui-egui/src/addons/pathtools/tangents.rs b/crates/ui-egui/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..1c1587a0d5 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents.rs @@ -0,0 +1,150 @@ +//! Common Tangents in the interface: one dialog for the tangent lines of two shapes and for circles joined by a smooth +//! bridge. It picks the kind of tangent, the centerline and Connect tangents (the two tangents of each kind joined into +//! one closed shape). With External, Straight keeps the tangent lines and Curved joins the circles along concave arcs +//! instead (the arcs' radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a +//! gap; the reach, unavailable with two circles selected; Keep Originals), as `addon.pathtools.bridge` does. It +//! previews on the canvas and runs `addon.pathtools.commonTangents` on OK. Smooth Bridge's command id opens the same +//! dialog with External and Curved on. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::general_lengths; + +use super::{COMMON_TANGENTS, TANGENT_KINDS}; + +/// Smooth Bridge's command, which opens this dialog with External and Curved on. +pub const BRIDGE: &str = "addon.pathtools.bridge"; +/// The kind of tangent the dialog opens with. +const TANGENTS: &str = "all"; +/// The tangents that Curved replaces with arcs. +const EXTERNAL: &str = "external"; +/// What joins the circles with External, and its labels; the first is the default. +const SIDES: [(&str, &str); 2] = [("straight", "Straight"), ("curved", "Curved")]; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; +const REACH: f64 = 10.0; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None }; + +/// Whether the fields ask for a curved bridge: External with Curved. +fn curved(fields: &DialogFields) -> bool { + fields.text("tangents") == Some(EXTERNAL) && fields.text("sides") == Some("curved") +} + +/// The command's parameters from the dialog's fields: the tangent lines' kind, centerline and Connect tangents, or for +/// a curved bridge the radius (or with Constant Gap the gap), the reach and Keep Originals. +fn params(fields: &DialogFields) -> Value { + if !curved(fields) { + return json!({ + "tangents": fields.text("tangents").unwrap_or(TANGENTS), + "centerline": fields.bool("centerline").unwrap_or(false), + "connect": fields.bool("connect").unwrap_or(false), + }); + } + let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); + if fields.bool("constantGap").unwrap_or(false) { + json!({ "tangents": EXTERNAL, "curved": true, "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "tangents": EXTERNAL, "curved": true, "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) + } +} + +/// Opens Common Tangents' dialog for the tangent lines. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + open_with(app, false) +} + +/// Opens Common Tangents' dialog with External and Curved on, for Smooth Bridge's command. +pub(crate) fn open_connected(app: &mut VectorcraftApp) -> Result { + open_with(app, true) +} + +fn open_with(app: &mut VectorcraftApp, bridge: bool) -> Result { + // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview + // replaces the selection with its result, with a selected group counting the objects inside it. + let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); + let fields = DialogFields::from_pairs([ + ("tangents", FieldValue::from(if bridge { EXTERNAL } else { TANGENTS })), + ("centerline", FieldValue::Bool(false)), + ("connect", FieldValue::Bool(bridge)), + ("sides", FieldValue::from(if bridge { "curved" } else { "straight" })), + ("constantGap", FieldValue::Bool(false)), + ("radius", FieldValue::Number(RADIUS)), + ("gap", FieldValue::Number(GAP)), + ("reach", FieldValue::Number(REACH)), + ("keepOriginals", FieldValue::Bool(false)), + ("many", FieldValue::Bool(many)), + ]); + let lengths = general_lengths(app); + dialogs::open(app, &SPEC, fields, move |fields| { + let kinds = TANGENT_KINDS.iter().map(|(label, id)| ((*id).to_owned(), tl!(label).into())).collect(); + let sides = SIDES.iter().map(|(id, label)| ((*id).to_owned(), tl!(label).into())).collect(); + let curved = || ["curved"]; + // Picking another kind of tangent goes back to Straight, so Curved only holds while External does. + let rows = vec![ + Param::new("tangents", tl!("Tangents:"), ParamKind::choice(kinds, Some(TANGENTS.to_owned()))).resets(["sides"]), + Param::new("centerline", tl!("Centerline"), ParamKind::bool(false)).enabled_when("sides", "straight"), + // A curved bridge is always connected. + Param::new("connect", tl!("Connect tangents"), ParamKind::bool(false)).enabled_when("sides", "straight").disabled_value(true), + Param::new("sides", tl!("Sides"), ParamKind::radio(sides, Some(SIDES[0].0.to_owned()))).visible_when("tangents", EXTERNAL), + Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) + .length(lengths) + .bounds(Some(*GAPS.start()), Some(*GAPS.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [true]) + .enabled_when_in("sides", curved()), + Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) + .unit(UnitKind::Percent) + .bounds(Some(*RADII.start()), Some(*RADII.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [false]) + .enabled_when_in("sides", curved()), + Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) + .length(lengths) + .bounds(Some(*REACHES.start()), Some(*REACHES.end())) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()) + .and_enabled_when_in("many", [true]), + Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + ]; + ParamDialog::new(COMMON_TANGENTS, tl!("Common Tangents"), rows).previews(true).values(Bind::bound(fields)) + }) +} + +/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the +/// objects inside it, at any depth; an object given twice, or with its group, counts once. +fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { + fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { + match &n.kind { + vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => { + out.insert(n.id); + } + } + } + let mut out = std::collections::BTreeSet::new(); + for n in ids.iter().filter_map(|&id| doc.node(id)) { + visit(n, &mut out); + } + out.len() +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/pathtools/tangents/tests.rs b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..c3f1b84163 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs @@ -0,0 +1,244 @@ +//! Common Tangents' dialog: the tangent lines, Connect tangents, External's Straight or Curved bridge, Smooth +//! Bridge's command opening it curved, the reach's availability, Cancel and the refusals on the status line. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{BRIDGE, COMMON_TANGENTS}; +use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; +use crate::tests::panel_harness::Panel; +use crate::{VectorcraftApp, menus}; + +fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() +} + +fn circles_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app +} + +fn geometry(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn type_number(panel: &mut Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +/// The geometry the command makes on `xs`'s circles with `params`. +fn expected(xs: &[f64], params: &Value) -> Vec { + let mut app = circles_app(xs); + app.session.execute(COMMON_TANGENTS, params).unwrap(); + geometry(&app) +} + +#[test] +fn the_menu_item_adds_the_tangent_lines_and_only_their_options_take_input() { + let xs = [100.0, 200.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + assert!(panel.enabled("Centerline") && panel.enabled("Tangents") && panel.enabled("Connect tangents")); + assert!(!panel.shows("Radius") && !panel.shows("Straight"), "the bridge's options wait for External"); + panel.click("Centerline"); + panel.frame(); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "all", "centerline": true, "connect": false})); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms), "the preview"); + assert_eq!(geometry(&panel.app()).len(), 2 + 5, "four tangents and the centerline beside the circles"); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn external_shows_straight_or_curved_and_curved_takes_the_bridge_options() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + let id = dialog_id(&panel.app()); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + assert!(panel.shows("Straight") && panel.shows("Radius"), "External shows the bridge's options"); + assert!(!panel.enabled("Radius") && !panel.enabled("Keep Originals"), "Straight keeps them unavailable"); + panel.click("Connect tangents"); + panel.frame(); + let straight = read(&panel.app(), id, super::params); + assert_eq!(straight, json!({"tangents": "external", "centerline": false, "connect": true})); + assert_eq!(geometry(&panel.app()), expected(&xs, &straight)); + assert_eq!(geometry(&panel.app()).len(), 3, "the circles and one closed shape"); + + panel.click("Curved"); + panel.frame(); + assert!(panel.enabled("Radius") && panel.enabled("Keep Originals") && !panel.enabled("Centerline")); + let curved = read(&panel.app(), id, super::params); + assert_eq!(curved, json!({"tangents": "external", "curved": true, "radius": 100.0, "reach": 10.0, "keepOriginals": false})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, &curved)); + assert_eq!(preview.len(), 1, "the bridge replaces the circles"); + + // Another kind of tangent goes back to Straight and the lines' options. + set(&panel.app(), id, "tangents", json!("internal")); + panel.frame(); + assert!(panel.enabled("Centerline") && !panel.shows("Curved")); + assert_eq!(read(&panel.app(), id, super::params)["tangents"], "internal"); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + panel.click("Curved"); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1, "one undo step"); +} + +#[test] +fn the_bridge_command_opens_the_dialog_connected_and_its_controls_reach_the_command() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Radius"), "External and Curved are on"); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut old = circles_app(&xs); + old.session.execute(BRIDGE, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&old), "the same outline Smooth Bridge makes"); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, ¶ms)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn a_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + let xs = [100.0, 124.0, 148.0, 300.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); +} + +#[test] +fn reach_counts_the_circles_inside_a_selected_group() { + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = circles_app(xs); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); + panel.click("OK"); + panel.frame(); + let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); + assert_eq!(inside, 1, "the circles in the group became one shape"); + } + // A group of two circles selected together with one of them: still two circles. + let mut app = circles_app(&[100.0, 124.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); +} + +#[test] +fn constant_gap_bridges_many_circles_within_reach() { + let mut app = circles_app(&[100.0, 124.0, 148.0, 300.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + menus::invoke(&mut app, BRIDGE, Value::Null); + let dialog = dialog_id(&app); + set(&app, dialog, "constantGap", json!(true)); + // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the four + // circles the command still bridges. + frame(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); + assert_eq!(many, Some(true), "Reach available for four circles"); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + assert!(confirm(&app, dialog), "OK is on"); + frame(&mut app); + let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); +} + +#[test] +fn the_status_line_says_why_a_selection_is_refused() { + // Connected: an ellipse is not a circle. + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 10.0); + let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, oval]})).unwrap(); + let original = geometry(&app); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + let why = "an ellipse whose width and height differ is not a circle"; + assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); + panel.click("OK"); + panel.frame(); + assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); + assert_eq!(geometry(&panel.app()), original); + assert_eq!(steps(&panel.app()), before, "no undo step"); + + // The lines: a circle inside another has none, and the warning says so. + let mut app = circles_app(&[150.0]); + let outer = app.run("shape.ellipse", json!({"x": 100, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let inner = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [inner, outer]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + let count = geometry(&panel.app()).len(); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before); + assert_eq!(geometry(&panel.app()).len(), count); + assert!(panel.app().ui.status.contains("inside the other"), "{}", panel.app().ui.status); +} diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 6ae9a2ae91..22428bef53 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,8 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status -//! ([`link_status`], #5526). +//! runs `addon.select.byArtboards` with the relation chosen; Select by Link Status +//! ([`link_status`], #5526); and Edit Points Only ([`points_only`]). use craft::behavior::{Selection, keyed}; use craft::i18n::Folder; @@ -27,6 +27,7 @@ use crate::VectorcraftApp; use crate::menus::{Sep, cp}; pub mod link_status; +pub mod points_only; /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; @@ -40,6 +41,8 @@ const LIST_ROWS: u16 = 9; pub fn menu() -> Vec { let mut v = vec![cp("Select by Artboards…", COMMAND, Value::Null), Sep]; v.extend(link_status::menu()); + v.push(Sep); + v.extend(points_only::menu()); v } diff --git a/crates/ui-egui/src/addons/select/points_only.rs b/crates/ui-egui/src/addons/select/points_only.rs new file mode 100644 index 0000000000..f4b0d157d2 --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only.rs @@ -0,0 +1,51 @@ +//! Edit Points Only in the interface: its item in Object › Plug-ins › Selection Tools and its +//! dialog, which previews the narrowed selection on the canvas and runs +//! `addon.select.editPointsOnly` on OK; Cancel puts the selection back. + +use std::borrow::Cow; + +use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; +use serde_json::{Map, Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::Spec; +use crate::dialogs::form; +use crate::menus::c; + +/// Edit Points Only: the dialog's key and the command its OK runs. +pub const COMMAND: &str = "addon.select.editPointsOnly"; + +static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The menu item. +pub fn menu() -> Vec { + vec![c("Edit Points Only…", COMMAND)] +} + +/// The dialog's rows. +fn rows() -> Vec { + vec![Param::new("segmentEnds", tl!("Keep Ends of Selected Segments"), ParamKind::bool(false))] +} + +/// The command's params for the dialog's `fields`. +fn params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&rows(), fields)) +} + +/// Opens the dialog on the active document, with the ends of selected segments left out. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + if app.session.active().is_none() { + return Err("no document".into()); + } + let mut opening = Map::new(); + opening.insert("segmentEnds".into(), json!(false)); + let fields = form::fields_of(&rows(), &opening); + crate::addons::dialogs::open(app, &SPEC, fields, |fields| { + ParamDialog::new(COMMAND, tl!("Edit Points Only"), Cow::Owned(rows())).previews(true).values(Bind::bound(fields)) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs new file mode 100644 index 0000000000..75ddaf5703 --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -0,0 +1,175 @@ +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; + +/// An app with a window and two rectangles: anchors 0 and 1 of the first selected, and segment 1 +/// of the second (whose ends are its anchors 1 and 2) beside its anchor 3. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(10), rect(100)); + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + app.run("select.anchorsMany", json!({"items": items})).unwrap(); + app.run("select.segments", json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + (app, a, b) +} + +fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() +} + +/// The selected anchors of `id`, and whether any segment is selected. +fn points(app: &VectorcraftApp, id: NodeId) -> (Option>, bool) { + let sel = &app.session.doc().unwrap().selection; + (sel.anchors.get(&id).cloned(), !sel.segments.is_empty()) +} + +#[test] +fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard() { + let (app, a, b) = app(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(false)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false), "the preview drops the segment and its ends"); + assert_eq!(points(&panel.app(), a).0, Some(refs(&[(0, 0), (0, 1)]))); + panel.focus("Keep Ends of Selected Segments"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + panel.frame(); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(true)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false), "the ends are kept as anchor points"); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(points(&app, b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step"); +} + +#[test] +fn ok_drops_puppet_pins_without_an_undo_step() { + for previewing in [true, false] { + let (mut app, a, b) = app(); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("object.puppetWarp", json!({"pins": [[35, 35]], "moved": [[35, 35]], "rest": true})).unwrap(); + assert!(app.session.doc().unwrap().doc.puppet.is_some()); + let undo = app.session.doc().unwrap().history.undo.len(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + if previewing { + host::frame(&mut app); + assert!(app.session.doc().unwrap().doc.puppet.is_none()); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + let st = app.session.doc().unwrap(); + assert!(st.doc.puppet.is_none()); + assert_eq!(st.selection.objects, vec![a, b]); + assert!(!app.session.in_interaction()); + assert_eq!(st.history.undo.len(), undo, "pin cleanup does not add an undo step"); + } +} + +#[test] +fn cancel_puts_the_selection_back() { + let (app, _, b) = app(); + let before = app.session.doc().unwrap().selection.clone(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false)); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); +} + +#[test] +fn successful_preview_and_confirmation_preserve_another_status() { + for previewing in [true, false] { + let (mut app, _, _) = app(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + app.status("The active text edit reported a warning."); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + assert!(!app.any_dialog_open()); + } +} + +#[test] +fn recovering_from_a_preview_error_preserves_a_later_status() { + for previewing in [true, false] { + for same_text in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected")); + let status = if same_text { app.ui.status.clone() } else { "Another command reported a warning.".to_owned() }; + app.status(status.clone()); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + } +} + +#[test] +fn keeping_segment_ends_clears_the_preview_error() { + for previewing in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(points(&app, a), (Some(refs(&[(0, 0), (0, 1)])), false)); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert!(!app.any_dialog_open()); + } +} + +#[test] +fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + let before = app.session.doc().unwrap().selection.clone(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index e5fde5725e..65fed545ca 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -709,7 +709,7 @@ mod cancel_tests { #[cfg(test)] mod tests { use craft::behavior::IconId; - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; use super::icon_for_shape; @@ -717,7 +717,7 @@ mod tests { /// would show the placeholder instead of the toolbar's icon. #[test] fn every_shape_button_shows_its_tools_icon() { - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8ddfe99310..b87001e4b5 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -9,7 +9,7 @@ use craft::ui::choice::ChoiceLook; use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, MoveBandCursor, QuietHeader, SectionRhythm}; use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; -use craft::ui::menu::MenuTitleLook; +use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; @@ -67,7 +67,7 @@ impl VectorcraftApp { /// once, gives Data Recovery the host's store and makes a view for each open document. pub fn new(mut session: Session, mut services: Services) -> Self { // Every entry point (desktop, web, tests) makes the app before its first pass. - craft::ui::primitives::register_app_icons(&super::icons::APP_ICONS); + super::icons::register(); craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS); // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); @@ -140,6 +140,7 @@ impl VectorcraftApp { text_nodes: Default::default(), momentary: None, hand: None, + zoom_tool: None, selection_box: None, selection_bounds: None, selection_marks: None, @@ -380,7 +381,12 @@ impl VectorcraftApp { } /// A window's raw input, before egui and the keys read it (the host's `raw_input_hook`). - pub fn raw_input(&self, ctx: &egui::Context, raw: &mut egui::RawInput) { + pub fn raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // AppKit consumes the key-down and winit can already have queued its key-up. + // Poll before the runtime orders the press and release in this frame's input. + if let Some(menu) = self.services.native_menu.as_mut() { + menu.poll(ctx); + } crate::type_editing::keep_layout_text(self, ctx, raw); } @@ -717,7 +723,13 @@ impl VectorcraftApp { export_progress::show(self, ui); // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); + let drawn_document = self.session.active().map(|st| (st.uid, st.revision)); dialogs::host::pump(self, &ctx); + // The canvas has already painted. A dialog can apply or roll back its preview + // on the final input frame, with no further mouse movement to wake the window. + if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document { + ctx.request_repaint(); + } prefs_dialog::show(self, ui); crate::shortcut_editor::show(self, ui); credits::open_taken_link(self); @@ -764,6 +776,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print let (theme, mode, accent) = theme::root_theme(prefs); let scaling = applied_ui_scaling(prefs.ui_scaling); let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); + // Painted tool cursors grow with UI Scaling only when Scale Cursor Proportional to UI is on. + root = root.cursor_follows_zoom(prefs.scale_cursor_with_ui); root.sizes = theme::app_sizes(); root.values.set(view::zoom_scheme(print, native_ppp)); root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); @@ -806,8 +820,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print root.values.set(ThumbRows::Tight); // The Layers Objects search field fills the filter bar up to its Filter button, as production's did. root.values.set(ObjectsSearch::Fill); - // The menu bar's titles are production's egui buttons: a push button high, 2 points beside the text, rounded. - root.values.set(MenuTitleLook::Button); + // The menu bar's titles are menu rows with the control padding (`space.pad.control`) on each side of the text. + root.values.set(MenuTitleLook::Row); + root.values.set(MenuTitlePad::Control); // The title bar and the panel headers keep the arrow, over the menu titles too, as production's did. root.values.set(MoveBandCursor::Arrow); // Document tabs show their title and its `*` in the label's semibold face, as production drew them. @@ -824,6 +839,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print root.escape_leaves_fields = true; // A held key repeats its command (Cmd+= keeps zooming in). root.shortcuts_repeat = true; + // The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the + // pointer. + root.pointer_scoped_field_wheel = true; root } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index b7ff421414..1298051ad8 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -129,11 +129,12 @@ impl VectorcraftApp { /// document without artboards they get neither. fn add_active_artboard(&self, id: &str, params: &mut Value) { let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + let clipboard_command = paste || matches!(id, "edit.copy" | "edit.cut"); if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch") && params.get("artboard").is_none() && !(paste && params.get("artboards").is_some()) && self.view().is_some() - && let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste) + && let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !clipboard_command) && let Some(p) = params.as_object_mut() { let picked = panels::artboards::picked(self, n); @@ -252,7 +253,7 @@ impl VectorcraftApp { } let spot_base = panels::color_guide::before_command(self); let plugins_before = dialogs::plugin::before_command(); - let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); + let r = crate::print::execute_listing_printers(self, id, ¶ms); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() && let Some(op) = completed_pathfinder_operation(id, ¶ms) diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index 57a9bf1086..33c7d37e28 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -331,10 +331,21 @@ pub fn wait_all(app: &mut VectorcraftApp) { wait_until(app, |_| false); } +#[cfg(test)] +thread_local! { + /// Run once on this thread when [`wait_until`] next starts to wait for a job's result, so a test + /// lets a held job finish only once the wait has started. + pub(crate) static ON_WAIT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// Apply the jobs' results as they arrive (in the order the jobs were started) until `ready` holds /// or no job is left. pub fn wait_until(app: &mut VectorcraftApp, ready: impl Fn(&VectorcraftApp) -> bool) { while !ready(app) && !app.background.jobs.is_empty() { + #[cfg(test)] + if let Some(waiting) = ON_WAIT.with_borrow_mut(Option::take) { + waiting(); + } let Some(done) = app.background.results.as_ref().and_then(|(_, rx)| rx.recv().ok()) else { // No result can arrive: the jobs can't finish. for job in std::mem::take(&mut app.background.jobs) { diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index cdf59a99f8..06c564f4c8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,6 +82,8 @@ pub struct CanvasCache { /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, pub hand: Option, + /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. + pub zoom_tool: Option, /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and /// Measure Type by Glyph Bounds). pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 08f859b025..73b97bce0f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,8 +5,8 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, - canvas_space, tool_pass, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ShownBars, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + canvas_space, tool_pass, with_canvas_space, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::primitives::PaintSlot; @@ -37,6 +37,7 @@ mod outline; mod overlays; pub(crate) mod panes; mod quick_pen_bar; +mod quick_pen_wheel; mod raster; pub(crate) mod rulers; pub(crate) mod selection; @@ -143,6 +144,8 @@ struct Body { context_key: bool, /// A view a compass or scroll bar edit made this pass. edited: Option, + /// The Quick Pen tool took this pass's wheel for its arc size ([`quick_pen_wheel::arc_size`]). + arc_view: Option, } /// Window `win`'s document in the framework canvas, filling the rest of `ui`. True when the canvas @@ -208,6 +211,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // cursors the tools are told about. let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; + let before_wheel = cv; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) .view(Bind::bound(&mut cv)) @@ -229,8 +233,40 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let mut body = Body::default(); let shown = canvas.show(ui, |ui, env| { - if let Some(space) = canvas_space(&env.env) { - body = show_body(app, ui, &space, tool_pass(&env.env).as_ref(), win, kind); + if let Some(mut space) = canvas_space(&env.env) { + let mut pass = tool_pass(&env.env); + let bar_paint = PaintSlot::reserve(ui.painter()); + let mut arc_view = space.target(); + if space.wheel().is_some_and(|w| !w.claimed && quick_pen_wheel::control_turn(app, &w)) { + arc_view.zoom = before_wheel.zoom; + arc_view.center = before_wheel.center; + arc_view.rotation = before_wheel.rotation; + for request in &queued { + request.command().apply(&mut arc_view, &target, Some(&layers), ppp, &scheme); + } + } + let arc_turn = if kind == BodyKind::Live && app.ui.screen_mode < 3 { + let mut bar_space = space; + if space.wheel().is_some_and(|w| w.claimed || quick_pen_wheel::control_turn(app, &w)) { + bar_space.set_view(arc_view); + } + let bar = with_canvas_space(ui, bar_space, |ui| quick_pen_bar::quick_pen_bar(app, ui, &bar_space)); + quick_pen_wheel::arc_size(app, ui.ctx(), &space, bar) + } else { + false + }; + let bar_shapes = bar_paint.take_after(ui.ctx()); + // The framework settles wheel navigation before the body. A claimed share uses the + // saved view for the controls, painting and tool host, including its first pass. + if arc_turn { + space.set_view(arc_view); + if let Some(pass) = pass.as_mut() { + pass.space = Some(space); + pass.view = Some(arc_view); + } + } + body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); + body.arc_view = arc_turn.then_some(arc_view); } }); let output = shown.output; @@ -243,16 +279,20 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, context_key, edited } = body; + let Body { reply, context_at, context_key, edited, arc_view } = body; let request = reply .as_ref() .and_then(|r| r.context.as_ref()) .map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key }) .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); - // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own. - let view_now = - if presenting && ui.input(|i| i.pointer.middle_down()) { given } else { edited.or(reply.and_then(|r| r.view)).or(output.view).unwrap_or(cv) }; + // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own, and a + // wheel turn the Quick Pen tool takes for its arc size leaves other view requests in place. + let view_now = if presenting && ui.input(|i| i.pointer.middle_down()) { + given + } else { + edited.or(reply.and_then(|r| r.view)).or(arc_view).or(output.view).unwrap_or(cv) + }; if let Some(view) = doc_windows::view_mut(app, win) { view.set_canvas(&view_now, scaling); // Fitted once, the view stays where it is moved. @@ -280,7 +320,15 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin /// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the /// display-only widgets over it, the picture last. -fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { +fn show_body( + app: &mut VectorcraftApp, + ui: &mut Ui, + space: &CanvasSpace, + pass: Option<&ToolPass>, + win: Win, + kind: BodyKind, + bar_shapes: Vec, +) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; let background = space.background(); @@ -319,7 +367,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O // The bars give way to a drag, not to a click. let dragging = in_gesture(app, ui.ctx()) && ui.input(|i| i.pointer.is_decidedly_dragging()); let task_bar = (app.ui.task_bar && !revolve_editing(app) && !strip && !dragging).then(|| task_bar::task_bar(app, ui, space)).flatten(); - quick_pen_bar::quick_pen_bar(app, ui, space); + PaintSlot::reserve(ui.painter()).extend(ui.ctx(), bar_shapes); contour_bar::contour_bar(app, ui, space); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, space, task_bar); @@ -418,7 +466,7 @@ fn clear_of_scroll_bars(app: &VectorcraftApp, ui: &Ui, rect: egui::Rect) -> egui if app.ui.screen_mode >= 2 { return rect; } - CanvasScrollbars::clear_of(ui, rect, false, false) + CanvasScrollbars::clear_of(ui, rect, false, ShownBars::Both) } /// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view diff --git a/crates/ui-egui/src/canvas/artboards.rs b/crates/ui-egui/src/canvas/artboards.rs index 605e7108d2..a6181ea805 100644 --- a/crates/ui-egui/src/canvas/artboards.rs +++ b/crates/ui-egui/src/canvas/artboards.rs @@ -31,7 +31,7 @@ pub(super) fn checker_of(setup: &vectorcraft_doc::DocSetup) -> Checker { } /// The page frames of document `st` seen through `view`: one per artboard, named "01 - name" with the -/// Artboard tool or several boards, filled with its paper or the transparency grid (nothing in Outline). +/// Artboard tool or several boards, filled with its paper or the transparency grid (white in Outline). /// Empty while the artboards are hidden. pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, view: &View, outline: bool) -> Vec { if !shows_artboards(app) { @@ -51,7 +51,7 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi frame = frame.name(format!("{:02} - {}", i + 1, ab.name)); } if outline { - frame + frame.fill(DataColor::new(Color32::WHITE)) } else if grid { frame.checker(checker_of(setup)) } else { diff --git a/crates/ui-egui/src/canvas/artboards/tests.rs b/crates/ui-egui/src/canvas/artboards/tests.rs index 742e798e63..19e0d91c11 100644 --- a/crates/ui-egui/src/canvas/artboards/tests.rs +++ b/crates/ui-egui/src/canvas/artboards/tests.rs @@ -29,9 +29,11 @@ fn the_artboard_tool_names_its_active_artboard_once() { assert!(names.iter().enumerate().all(|(i, n)| n.as_deref().is_some_and(|n| n.starts_with(&format!("{:02} - ", i + 1))))); let mut single = app_with(1); use_tool(&mut single, "selection"); - assert!(frames_of(&single, false).iter().all(|f| f.name.is_none())); + let unnamed = frames_of(&single, false); + assert!(unnamed.len() == 1 && unnamed[0].name.is_none(), "{:?}", unnamed.len()); use_tool(&mut single, "artboard"); - assert!(frames_of(&single, false).iter().all(|f| f.name.is_some())); + let named = frames_of(&single, false); + assert!(named.len() == 1 && named[0].name.is_some(), "{:?}", named.len()); use_tool(&mut app, "artboard"); assert_eq!(frames_of(&app, false).iter().filter(|f| f.name.is_some()).count(), 2); } @@ -47,16 +49,20 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() { } #[test] -fn outline_has_a_white_canvas_line_edges_and_no_paper() { +fn outline_has_white_artboards_on_a_white_canvas_with_line_edges() { let _view = crate::testing::DefaultProofView::new(); let app = app_with(2); let st = app.session.active().unwrap(); assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE))); assert_eq!(border(true), PageBorder::Line); - assert!(frames_of(&app, true).iter().all(|f| f.fill.is_none())); + let outline = frames_of(&app, true); + assert_eq!(outline.len(), 2, "a frame for each artboard"); + assert!(outline.iter().all(|f| f.fill == Some(PageFill::Color(DataColor::new(Color32::WHITE))))); assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Default); assert_eq!(border(false), PageBorder::DropShadow); - assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some())); + let preview = frames_of(&app, false); + assert_eq!(preview.len(), 2, "a frame for each artboard"); + assert!(preview.iter().all(|f| f.fill.is_some())); } /// Overprint Preview, and Separations Preview, which turns it on, draw a white canvas around the artboards and no @@ -83,7 +89,9 @@ fn overprint_preview_draws_a_white_canvas_without_shadows() { assert_eq!(border(false), PageBorder::DropShadow, "{at}"); } assert_eq!(border(true), PageBorder::Line, "{at}"); - assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()), "{at}"); + let frames = frames_of(&app, false); + assert_eq!(frames.len(), 2, "{at}: a frame for each artboard"); + assert!(frames.iter().all(|f| f.fill.is_some()), "{at}"); } } app.run("view.overprintPreview", json!({"on": true})).unwrap(); @@ -182,7 +190,9 @@ fn paper_is_the_artboard_color_times_the_simulated_paper() { assert_eq!(artboard_paper(&ab, Color32::WHITE), Color32::from_rgb(51, 102, 153)); // The frame carries the same fill. app.run("view.transparencyGrid", json!({})).unwrap(); - assert!(frames_of(&app, false).iter().all(|f| matches!(f.fill, Some(PageFill::Checker(_))))); + let frames = frames_of(&app, false); + assert_eq!(frames.len(), 1, "the artboard's frame"); + assert!(frames.iter().all(|f| matches!(f.fill, Some(PageFill::Checker(_))))); } #[test] @@ -205,7 +215,9 @@ fn the_transparency_grid_follows_each_document_and_the_view_menu_label() { assert_eq!(menus::dynamic_label(&app, "view.transparencyGrid", ""), "Show Transparency Grid"); assert_eq!(app.run("view.transparencyGrid", json!({})).unwrap(), json!({"on": true})); assert!(shows_transparency_grid(app.session.active().unwrap())); - assert!(frames_of(&app, false).iter().all(|f| matches!(f.fill, Some(PageFill::Checker(_))))); + let frames = frames_of(&app, false); + assert_eq!(frames.len(), 1, "the artboard's frame"); + assert!(frames.iter().all(|f| matches!(f.fill, Some(PageFill::Checker(_))))); assert_eq!(menus::dynamic_label(&app, "view.transparencyGrid", ""), "Hide Transparency Grid"); app.run("document.activate", json!({"index": 0})).unwrap(); assert!(!shows_transparency_grid(app.session.active().unwrap())); diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index d95cdc02e1..5034e23f17 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -73,15 +73,20 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } } -/// What the start screen's user did. +/// What the start screen's user did. A command that fails says why in the status bar (#6160). fn run_action(app: &mut VectorcraftApp, action: StartAction) { + fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) { + if let Err(e) = app.run(id, params) { + app.status(e); + } + } match action { - StartAction::New => drop(app.run("file.newDialog", json!({}))), - StartAction::Open => drop(app.run("file.open", json!({}))), + StartAction::New => run(app, "file.newDialog", json!({})), + StartAction::Open => run(app, "file.open", json!({})), // A failure is reported to the user there. StartAction::OpenRecent(path) => drop(crate::io::open_reporting(app, &path.to_string_lossy())), - StartAction::UseTemplate(name) => drop(app.run("file.new", json!({ "preset": name }))), - StartAction::ClearRecent => drop(app.run("file.clearRecent", json!({}))), + StartAction::UseTemplate(name) => run(app, "file.new", json!({ "preset": name })), + StartAction::ClearRecent => run(app, "file.clearRecent", json!({})), StartAction::RemoveRecent(path) => app.ui.recent_files.retain(|recent| std::path::Path::new(recent) != path), StartAction::RevealRecent(path) => { // PLAN: `io::export` is a private module of `io`; `reveal_path` needs a re-export from io.rs (unowned). diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index c07aa1da14..9b2846847e 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -26,20 +26,20 @@ use super::{Ui, VectorcraftApp, json}; /// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and /// no gesture is under way on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on -/// ([`VectorcraftApp::try_select_tool`]). -pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { +/// ([`VectorcraftApp::try_select_tool`]). Returns the toolbar's rect when it showed. +pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { - return; + return None; } // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) if super::tool_adapter::in_gesture(app, ui.ctx()) { - return; + return None; } // A middle-button drag pans the canvas, which hides the toolbar as a tool's drag does. if ui.input(|i| i.pointer.middle_down() && i.pointer.press_origin().is_some_and(|p| space.view.rect.contains(p))) { - return; + return None; } - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + let uid = app.session.active().map(|st| st.uid)?; let view = app.view_info(); let end = app.session.tool_drawing_end(view); let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view); @@ -112,4 +112,5 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva { app.ui.status = e; } + shown.output.rect.is_positive().then_some(shown.output.rect) } diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs new file mode 100644 index 0000000000..96616e3b1d --- /dev/null +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -0,0 +1,149 @@ +//! Ctrl+wheel over the canvas with the Quick Pen tool: the arc size, in place of the view. +//! +//! Public behavior: Ctrl + scroll on a trackpad makes the arc size larger or smaller, on Windows +//! and on macOS alike +//! ([Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)). +//! VectorCraft's own rules: a mouse wheel turned with Ctrl does the same; a mouse wheel makes one +//! step of 15°, as `[` and `]` do, for each net whole wheel line (at least one for each nonzero share +//! of wheel motion the canvas reads), and a touchpad makes one step for each wheel line of its +//! gesture's motion; up makes the arc larger and down smaller, and sideways motion makes no step +//! (with Ctrl on Windows and Linux, where the wheel reaches the canvas as a zoom, sideways motion +//! counts as up and down); and momentum after the fingers lift makes no step. +//! +//! Everything here is read from the canvas's share of the framework's wheel (`space.wheel()`): its +//! modifiers, its device, its motion in lines (`lines`, or `zoom_lines` for a wheel that reaches the +//! canvas as a zoom), its gesture's motion so far (`gathered`, `zoom_gathered`), the keys held during +//! the gesture (`held`) and whether the gesture began under a modal window (`modal`). + +use craft::behavior::{Wheel, WheelSource, WheelUnit}; +use craft::keymap::{Mods, Platform}; +use craft::ui::canvas::CanvasSpace; + +use super::{VectorcraftApp, json}; + +/// Most steps one share of the wheel makes: from 1° to 359° is fewer than 24 steps of 15°. +const MOST_STEPS: f32 = 24.0; + +/// How far a line's worth of motion may fall short of a whole line and still count as one. +const LINE_SLACK: f32 = 1e-3; + +/// The Control key alone: Ctrl on Windows and Linux, which the keymap folds into `cmd`, and the +/// Control key on macOS, where `cmd` is ⌘. +fn ctrl_alone(m: Mods, os: Platform) -> bool { + let control = if os.is_mac() { m.ctrl && !m.cmd } else { m.cmd && !m.ctrl }; + control && !(m.alt || m.shift) +} + +/// The share's up and down motion in wheel lines, up positive. A wheel turned with egui's zoom +/// modifier (Ctrl on Windows and Linux) reaches the canvas as a zoom, and the framework counts its +/// lines in `zoom_lines`; sideways motion there adds to up and down, as egui's zoom factor does. +/// Points of a touchpad or a browser are lines of `line` points. +fn lines(wheel: &Wheel, line: f32) -> f32 { + // Wheel exposes only the share's signed totals, without individual events or separate up/down + // counts. Opposite notches in one pass cancel; their order and steps at the arc limits cannot + // be recovered. Count the net lines the framework reports. + let d = if wheel.zoom_lines != egui::Vec2::ZERO { + wheel.zoom_lines.x + wheel.zoom_lines.y + } else if wheel.scroll.y != 0.0 { + if wheel.unit == WheelUnit::Line { wheel.lines.y } else { wheel.scroll.y / line } + } else { + 0.0 + }; + if d.is_finite() { d } else { 0.0 } +} + +/// Whether `wheel`, of `lines` wheel lines, comes from a touchpad and not from a mouse wheel's +/// notches. egui names the source on macOS and reports it unknown elsewhere. There, point motion +/// (Wayland, a Windows precision touchpad) and line motion that is not whole lines (Windows and X11) +/// count as a touchpad. A browser reports a mouse wheel in points, so the web build counts only line +/// motion that is not whole lines. +fn fine(wheel: &Wheel, lines: f32) -> bool { + match wheel.source { + WheelSource::Trackpad | WheelSource::Momentum => true, + WheelSource::Unknown if wheel.unit == WheelUnit::Point => !cfg!(target_arch = "wasm32"), + WheelSource::Unknown => (lines - lines.round()).abs() >= LINE_SLACK, + _ => false, + } +} + +pub(super) fn control_turn(app: &VectorcraftApp, wheel: &Wheel) -> bool { + let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); + let mods = if fine(wheel, lines(wheel, line)) { wheel.held } else { wheel.mods }; + let scrolling = + (wheel.scroll.is_finite() && wheel.scroll != egui::Vec2::ZERO) || (wheel.zoom_lines.is_finite() && wheel.zoom_lines != egui::Vec2::ZERO); + ctrl_alone(mods, crate::keymap::platform()) && (wheel.claimed || scrolling) +} + +/// Whole lines in `v`, toward zero, with [`LINE_SLACK`] for rounding. +fn whole(v: f32) -> f32 { + (v + LINE_SLACK * v.signum()).trunc() +} + +/// The steps `wheel` makes, up positive: a mouse wheel's whole lines, at least one; one for a share +/// of points or pages from a mouse; and for a touchpad the whole lines of the motion the tool took in +/// this turn, with the fraction kept in `rest`. Momentum after the fingers lift makes no step. +fn steps(wheel: &Wheel, line: f32, rest: &mut f32) -> f32 { + if wheel.source == WheelSource::Momentum { + return 0.0; + } + let d = lines(wheel, line); + if d == 0.0 { + return 0.0; + } + if fine(wheel, d) { + *rest += d; + let steps = whole(*rest); + *rest -= steps; + return steps.clamp(-MOST_STEPS, MOST_STEPS); + } + let notches = if wheel.unit == WheelUnit::Line { (d.abs() + LINE_SLACK).trunc() } else { 1.0 }; + d.signum() * notches.clamp(1.0, MOST_STEPS) +} + +/// With the Quick Pen tool active, the wheel share the canvas read this pass (`wheel`), turned with +/// the Control key alone and not over the Quick Pen toolbar (`bar`), makes the arc size larger (up) +/// or smaller (down). A touchpad gesture counts the keys held at any point of it, keys tapped +/// between its events included. No step is made while a modal window is up, nor for the rest of a +/// turn begun under one. Returns true while the tool takes the turn, so the view does not zoom or +/// scroll for the rest of it. A turn is the framework's wheel gesture, and the tool keeps no state of +/// its own: it claims each share it reads (`CanvasSpace::claim_wheel`), recording as `spent.x` the +/// touchpad motion it kept, in wheel lines, so `claimed_spent.x` is the motion of the turn not yet +/// turned into a step. +pub(super) fn arc_size(app: &mut VectorcraftApp, ctx: &egui::Context, space: &CanvasSpace, bar: Option) -> bool { + let Some(w) = space.wheel() else { return false }; + // The framework marks a turn a modal layer held (`modal`); a turn that reaches the canvas while one + // of the app's own modal windows is up is marked too, and stays muted until the framework starts a + // new one. + let app_modal = crate::panel_docking::modal_window_up(app); + if app_modal { + space.mark_wheel_modal(ctx); + } + let muted = w.modal || app_modal; + let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); + let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); + let over_content = w.at.is_some_and(|at| space.view.rect.contains(at)); + let quick_pen = app.session.tool_id() == vectorcraft_tools::quickpen::ID; + let mut taken = w.claimed; + let mut runs = 0.0; + if quick_pen && !muted && !over_bar && over_content && control_turn(app, &w) { + let mut rest = w.claimed_spent.x; + let made = steps(&w, line, &mut rest); + // A share of a gesture another scroller owns cannot be claimed; the tool still takes it, as the + // canvas's output keeps the view for this pass. + space.claim_wheel(ctx, egui::vec2(rest - w.claimed_spent.x, 0.0)); + taken = true; + runs = made; + } + let cmd = if runs > 0.0 { "tool.quickPen.arcLarger" } else { "tool.quickPen.arcSmaller" }; + for _ in 0..(runs.abs() as u32) { + match app.run(cmd, json!({})) { + Ok(serde_json::Value::Bool(true)) => {} + Ok(_) => break, + Err(e) => { + app.ui.status = e; + break; + } + } + } + quick_pen && taken +} diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index dd2b85fcca..4f50576df8 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -29,7 +29,6 @@ use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). -// PLAN: BezierOverlay selects anchors of every path under `HandlesShown`, so a whole-selected container draws handles that the old marks hid outside Direct Selection. /// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points. const ANCHOR_AT_DEFAULT_SIZE: f32 = 5.0; @@ -60,6 +59,12 @@ pub(super) struct Anchors { pub paths: Vec, /// The selected anchors and the selected segment. pub selection: PathSelection, + /// The paths whose anchors show selected without direction handles: paths selected whole, or inside a container + /// selected whole, under a tool that does not drag handles, and the paths inside a container selected whole under + /// one that does ([`vectorcraft_tools::catalog::edits_anchors`]). + pub plain: Vec, + /// Every anchor of `plain`, selected. + pub plain_selection: PathSelection, /// Anchors as squares, or as circles under the Curvature tool. pub shown: AnchorsShown, /// Whose direction handles show. @@ -259,15 +264,21 @@ fn grid_path(key: u64, points: impl Iterator, color: Color32) -> E /// The anchors and handles of the selection. An object selected whole has every anchor selected, and so do the /// paths inside a group, compound path or clip group selected whole; with Direct Selection's partial selection only -/// the chosen anchors are, and a selected segment hollows the others. `tool_points` is whether the tool draws its own -/// points (the Curvature tool while it draws), which leaves nothing here. `tool` is the tool whose marks show -/// ([`super::shown_tool`]). Nothing too big to outline, and nothing during Halftone Preview. +/// the chosen anchors are, and a selected segment hollows the others. Direction handles show for a partial selection's +/// anchors, for a selected segment, and for a path selected whole when `tool` drags handles +/// ([`vectorcraft_tools::catalog::edits_anchors`]); every other path goes to [`Anchors::plain`], whose anchors show +/// without handles. `tool_points` is whether the tool draws its own points (the Curvature tool while it draws), which +/// leaves nothing here. `tool` is the tool whose marks show ([`super::shown_tool`]). Nothing too big to outline, and +/// nothing during Halftone Preview. pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> Anchors { let curvature = tool == "curvature"; + let drags_handles = vectorcraft_tools::catalog::edits_anchors(tool); let prefs = &app.session.prefs; let mut out = Anchors { paths: vec![], selection: PathSelection::default(), + plain: vec![], + plain_selection: PathSelection::default(), shown: if curvature { AnchorsShown::Curvature } else { AnchorsShown::All }, handles: if prefs.show_handles_multiple_anchors { HandlesShown::Selected } else { HandlesShown::OneAnchor }, segment_mark: SegmentMark::Line, @@ -279,6 +290,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; + let mut plain: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; @@ -295,8 +307,15 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin return; } let NodeKind::Path { path, .. } = &c.kind else { return }; - out.paths.push(edit_path(c.id.0, path, color)); let segments = sel.segments.get(&c.id); + // The handles the tools drag ([`vectorcraft_tools::direct`]'s `handle_anchors`): a partial selection's, a + // selected segment's, and those of a path selected itself under a tool that edits anchors. + if partial.is_none() && segments.is_none() && !(drags_handles && c.id == *id) { + out.plain.push(edit_path(c.id.0, path, color)); + plain.push((c.id.0, path.anchors().map(|(si, ai, _)| KnotRef::new(si, ai)).collect())); + return; + } + out.paths.push(edit_path(c.id.0, path, color)); if let Some(&(si, seg)) = segments.and_then(|s| s.iter().next()) { segment.get_or_insert((c.id.0, KnotRef::new(si, seg))); } @@ -326,6 +345,14 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin ); selection.others = by_key(chosen.into_iter().filter(|(key, _)| Some(*key) != primary)); out.selection = selection; + // `show` draws `plain` with `HandlesShown::OneAnchor`, which shows handles only while one anchor is selected. A + // lone anchor is drawn with its handles retracted instead; the selection's outline still draws its path. + if plain.iter().map(|(_, knots)| knots.len()).sum::() == 1 { + for knot in out.plain.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { + (knot.in_ctrl, knot.out_ctrl) = (knot.anchor, knot.anchor); + } + } + out.plain_selection.others = by_key(plain); out } @@ -660,6 +687,15 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .path_options(&anchors.options) .show_at(ui, rect); } + if !anchors.plain.is_empty() { + let mut paths = anchors.plain.clone(); + let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) + .tool(BezierTool::Anchors) + .handles(HandlesShown::OneAnchor) + .anchors(anchors.shown) + .path_options(&anchors.options) + .show_at(ui, rect); + } let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); @@ -734,7 +770,7 @@ impl SelectionMarks { o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift)); o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array()); } - for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { + for knot in self.anchors.paths.iter_mut().chain(&mut self.anchors.plain).flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { knot.anchor += by; knot.in_ctrl += by; knot.out_ctrl += by; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index e413a5655c..42e0bc620b 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -50,6 +50,11 @@ fn marks(app: &VectorcraftApp) -> Anchors { anchors(app, app.session.active().unwrap(), app.session.tool_id(), false) } +/// Every path whose anchors show, with handles or without. +fn shown_paths(anchors: &Anchors) -> Vec<&EditPath> { + anchors.paths.iter().chain(&anchors.plain).collect() +} + fn all_selected(selection: &PathSelection) -> usize { selection.anchors.len() + selection.others.iter().map(|(_, knots)| knots.len()).sum::() } @@ -215,7 +220,7 @@ fn a_clip_group_over_a_huge_path_shows_its_clipping_path() { vec![vectorcraft_geom::Rect::new(100.0, 100.0, 200.0, 200.0)], "the square's outline, not the bounds of the huge art" ); - assert_eq!(marks(&app).paths.iter().map(|p| p.anchor_count()).sum::(), 4, "and its four anchors"); + assert_eq!(shown_paths(&marks(&app)).iter().map(|p| p.anchor_count()).sum::(), 4, "and its four anchors"); } #[test] @@ -228,13 +233,13 @@ fn a_huge_selection_shows_its_bounds_instead_of_every_outline() { assert_eq!((huge.len(), huge[0].0, huge[0].1.len()), (1, color, 1), "one bounds path in the layer colour"); let st = app.session.active().unwrap(); assert!(outlines(&app, st)[0].paths[0].elements().len() < 10, "a rectangle, not the outline"); - assert!(marks(&app).paths.is_empty(), "no anchors either"); + assert!(shown_paths(&marks(&app)).is_empty(), "no anchors either"); assert!(dots(&app, st).origins.is_empty()); app.run("edit.undo", json!({})).unwrap(); app.run("path.create", json!({"d": format!("M20 20 {} Z", points(200))})).unwrap(); let st = app.session.active().unwrap(); assert!(outlines(&app, st)[0].paths[0].elements().len() > 200, "a path of few points is outlined whole"); - assert_eq!(marks(&app).paths.len(), 1); + assert_eq!(shown_paths(&marks(&app)).len(), 1); } #[test] @@ -389,7 +394,7 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { app.run("select.set", json!({"ids": [group.0]})).unwrap(); let st = app.session.active().unwrap(); let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); - let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::>(); let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); (outlined, anchored, hovered) }; @@ -422,7 +427,7 @@ fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { app.run("select.set", json!({"ids": [group.0]})).unwrap(); let st = app.session.active().unwrap(); let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); - let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::>(); let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); (outlined, anchored, hovered) }; @@ -554,9 +559,64 @@ fn the_anchors_of_a_container_selected_whole_draw_selected() { app.select_tool("directSelection"); app.run("select.set", json!({"ids": [group.0]})).unwrap(); let shown = marks(&app); - // The ellipse's four anchors and the square's four. - assert_eq!(all_selected(&shown.selection), 8); - assert_eq!(shown.paths.len(), 2); + // The ellipse's four anchors and the square's four, drawn without handles: the tools drag only the handles of a + // path selected itself. + assert_eq!(all_selected(&shown.plain_selection), 8); + assert_eq!(shown.plain.len(), 2); + assert!(shown.paths.is_empty() && all_selected(&shown.selection) == 0, "no member's handles show"); +} + +/// The Selection tool shows a path selected whole with every anchor selected and no direction handles; Direct +/// Selection shows the same path's handles, and a partial selection's anchors keep theirs under either tool. +#[test] +fn the_selection_tool_shows_a_whole_paths_anchors_without_handles() { + let (mut app, curve) = scene(); + let count = { + let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(curve).unwrap().kind else { panic!("a path") }; + path.anchor_count() + }; + app.select_tool("selection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let shown = marks(&app); + assert!(shown.paths.is_empty(), "no path of the Selection tool's marks shows handles"); + assert_eq!(shown.plain.iter().map(|p| p.key).collect::>(), vec![curve.0]); + assert_eq!(all_selected(&shown.plain_selection), count, "every anchor draws selected"); + + app.select_tool("directSelection"); + let direct = marks(&app); + assert!(direct.plain.is_empty(), "Direct Selection draws the path with its handles"); + assert_eq!((direct.selection.path, direct.selection.anchors.len()), (Some(curve.0), count)); + + app.select_tool("selection"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + let partial = marks(&app); + assert!(partial.plain.is_empty(), "a partial selection keeps its anchor's handles"); + assert_eq!(partial.selection.anchors, vec![KnotRef::new(0, 2)]); +} + +/// A lone anchor selected whole under the Selection tool is drawn with its handles retracted, since the overlay shows +/// handles while one anchor is selected. +#[test] +fn a_lone_anchor_selected_whole_shows_no_handles() { + let mut app = blank(); + let point = id_of(&app.run("path.create", json!({"d": "M40 40"})).unwrap()); + app.run("path.setHandle", json!({"id": point.0, "anchor": 0, "which": "out", "x": 60, "y": 10, "independent": true})).unwrap(); + let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(point).unwrap().kind else { panic!("a path") }; + assert_eq!((path.anchor_count(), path.subpaths[0].anchors[0].h_out), (1, Point::new(60.0, 10.0)), "one anchor with a handle"); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [point.0]})).unwrap(); + let shown = marks(&app); + assert_eq!(all_selected(&shown.plain_selection), 1); + let knots: Vec<_> = shown.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).collect(); + assert_eq!(knots.len(), 1); + assert!(knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor), "the lone anchor's handles are retracted"); + + // Two anchors keep their handles in the marks: the overlay shows none while more than one is selected. + let curve = id_of(&app.run("path.create", json!({"d": "M40 140 C60 110 90 110 110 140"})).unwrap()); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let two = marks(&app); + assert_eq!(all_selected(&two.plain_selection), 2); + assert!(two.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).any(|k| k.out_ctrl != k.anchor), "the curve keeps its shape"); } #[test] @@ -844,9 +904,9 @@ fn the_outline_revision_follows_what_is_drawn() { #[test] fn an_empty_selection_has_no_marks() { let (mut app, _) = scene(); - assert!(!seen(&app).is_empty() && !marks(&app).paths.is_empty()); + assert!(!seen(&app).is_empty() && !shown_paths(&marks(&app)).is_empty()); app.run("select.none", json!({})).unwrap(); - assert!(seen(&app).is_empty() && marks(&app).paths.is_empty()); + assert!(seen(&app).is_empty() && shown_paths(&marks(&app)).is_empty()); let st = app.session.active().unwrap(); assert_eq!(dots(&app, st).centers.len() + dots(&app, st).origins.len(), 0); } @@ -891,7 +951,7 @@ thread_local! { fn kept(app: &VectorcraftApp) -> (Vec>, usize) { let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); let boxes = marks.outlines.iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect(); - (boxes, all_selected(&marks.anchors.selection)) + (boxes, all_selected(&marks.anchors.selection) + all_selected(&marks.anchors.plain_selection)) } // Whole-app frames build the selection's marks once for each change: none in frames that change nothing, one after @@ -914,7 +974,8 @@ fn the_canvas_builds_the_selection_marks_once_per_change() { assert_eq!(frames(&mut app, 5), 1, "a new selection builds its marks once"); let st = app.session.active().unwrap(); let boxes = outlines(&app, st).iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect::>(); - assert_eq!(kept(&app), (boxes, all_selected(&marks(&app).selection))); + let shown = marks(&app); + assert_eq!(kept(&app), (boxes, all_selected(&shown.selection) + all_selected(&shown.plain_selection))); app.select_tool("directSelection"); assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once"); } @@ -932,7 +993,7 @@ fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let origin = Point::new(boards[1].x0 + 10.0, boards[1].y0 + 15.0); + app.run("shape.rectangle", json!({"x": origin.x, "y": origin.y, "width": 20, "height": 20})).unwrap(); + app.views[0].artboard = 0; + app.run("edit.copy", json!({})).unwrap(); + app.views[0].artboard = 2; + let pasted = app.run("edit.pasteInPlace", json!({})).unwrap(); + let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap()); + let bounds = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap(); + assert_eq!(bounds.origin(), origin + (boards[2].origin() - boards[0].origin())); +} + /// A Shift-click with the Selection tool on an empty spot inside an artboard makes it the active /// one and keeps the selection, and Align to Artboard then aligns the objects to it unless the /// call names another artboard. @@ -880,6 +897,58 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); } +/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its +/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the +/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts +/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new +/// app, at most 20 times, until the other catalogs held still through it. +#[test] +fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let catalogs = || { + ( + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + crate::scripts_menu::revision(), + crate::dialogs::proof_setup::saved_revision(), + ) + }; + let run = || { + let (mut app, ctx, xf) = rectangle_tool(); + let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0))); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + for _ in 0..2 { + app_step(&mut app, &ctx, vec![]); + } + let none = egui::Modifiers::NONE; + let mut steps = vec![vec![primary(from, true, none)]]; + steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); + steps.push(vec![primary(to, false, none)]); + steps.extend([vec![], vec![], vec![]]); + let mut rebuilt = vec![]; + for events in steps { + let before = app.menus.rebuilds; + app_step(&mut app, &ctx, events); + rebuilt.push(app.menus.rebuilds - before); + } + (app, rebuilt) + }; + let (app, rebuilt) = (0..20) + .find_map(|_| { + let before = catalogs(); + let out = run(); + (catalogs() == before).then_some(out) + }) + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle"); + assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle"); +} + /// #6369: only the selection box remains over the temporary halftone, and the original /// selection's outlines come back when Preview is turned off or the dialog is cancelled. #[test] diff --git a/crates/ui-egui/src/canvas/tests_edge_scroll.rs b/crates/ui-egui/src/canvas/tests_edge_scroll.rs index 167f938861..3a67ee6840 100644 --- a/crates/ui-egui/src/canvas/tests_edge_scroll.rs +++ b/crates/ui-egui/src/canvas/tests_edge_scroll.rs @@ -139,3 +139,57 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() { assert_eq!(center(&app), c0); frame(&mut app, &ctx, vec![button(edge, false)]); } + +#[test] +fn a_freehand_stroke_at_the_edge_keeps_the_artwork_stationary() { + let (mut app, ctx, original) = zoomed_in("pencil"); + let rect = app.canvas_view().unwrap().rect; + let start = rect.center() - vec2(120.0, 60.0); + let edge = pos2(rect.right() - 2.0, start.y + 40.0); + let initial = center(&app); + let nodes = |app: &VectorcraftApp| { + let mut count = 0; + app.session.active().unwrap().doc.walk(|_| count += 1); + count + }; + let before = nodes(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(15.0, 25.0))]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); + for _ in 0..5 { + frame(&mut app, &ctx, vec![]); + assert_eq!(center(&app), initial); + } + frame(&mut app, &ctx, vec![button(edge, false)]); + assert!(nodes(&app) > before, "the pencil drew a new path"); + assert!(app.session.active().unwrap().doc.node(original).is_some()); +} + +#[test] +fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() { + let (mut app, ctx, _) = zoomed_in("zoom"); + app.session.prefs.animated_zoom = false; + let rect = app.canvas_view().unwrap().rect; + let position = rect.center(); + let zoom = |app: &VectorcraftApp| app.view().unwrap().zoom; + let initial = zoom(&app); + for pressed in [true, false] { + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(position), button(position, pressed)]); + } + let enlarged = zoom(&app); + assert!(enlarged > initial, "click should zoom in: {initial} -> {enlarged}"); + let modifiers = egui::Modifiers::ALT; + for pressed in [true, false] { + let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(modifiers), event]); + } + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let reduced = zoom(&app); + assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}"); + let start = position - vec2(90.0, 65.0); + let end = position + vec2(80.0, 55.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]); + frame(&mut app, &ctx, vec![button(end, false)]); + assert!(zoom(&app) > reduced, "the marquee should fit its region to the view"); +} diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 64dca524b3..52f2247f42 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -93,6 +93,17 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() { } } +/// Painted tool cursors keep their size under UI Scaling unless Scale Cursor Proportional to UI +/// is on. +#[test] +fn tool_cursors_follow_ui_scaling_only_with_the_cursor_preference() { + let mut prefs = vectorcraft_engine::Prefs { ui_scaling: 2.0, ..vectorcraft_engine::Prefs::default() }; + assert!(!prefs.scale_cursor_with_ui, "the preference starts off"); + assert!(!crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "off: the cursor keeps its size at 200%"); + prefs.scale_cursor_with_ui = true; + assert!(crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "on: the cursor grows with the interface"); +} + #[test] fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() { let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0)); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index cc2750f2a4..8b2b35db16 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -463,7 +463,14 @@ impl CanvasTool for SessionTool<'_> { if claim(&mut app, EngineKey::Left) { claims = claims.nudges(); } - if claim(&mut app, EngineKey::AltTap) { + // A lone Alt while the canvas has the keys is the tools' modifier let go without a click: the canvas takes it, + // so it does not give the menu bar the keys and the next tool letter still chooses its tool. F10 and Alt with + // a letter still reach the bar, and a lone Alt in a field or the bar keeps the framework's rule. + let canvas_has_keys = app + .ui_ctx + .as_ref() + .is_some_and(|ctx| !ctx.egui_wants_keyboard_input() && !craft::ui::menu::bar::is_focused(ctx) && !craft::ui::menu::bar::is_open(ctx)); + if canvas_has_keys || claim(&mut app, EngineKey::AltTap) { claims = claims.alt_tap(); } claims @@ -590,7 +597,9 @@ impl CanvasTool for SessionTool<'_> { } fn autoscrolls(&self) -> bool { - !self.carrying.get() && !self.view_only() + // Sampled freehand tools trace the pointer on the artwork. Scrolling + // under a held pen would extend the stroke without another sample. + !self.carrying.get() && !self.view_only() && !self.app().session.tool_wants_samples() } fn view_only(&self) -> bool { @@ -651,18 +660,30 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { picked - } else if app.session.tool_id() == "hand" && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() { + } else if matches!(app.session.tool_id(), "hand" | "zoom") && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() { let options = crate::app::view::navigation(&app.session.prefs); - let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options)); - hand.options = options; - let response = host_run(app, ui, pass, &mut hand); + let response = if app.session.tool_id() == "zoom" { + app.canvas.hand = None; + let mut zoom = app.canvas.zoom_tool.take().unwrap_or_else(|| craft::ui::canvas::ZoomTool::new(options)); + zoom.options = options; + let response = host_run(app, ui, pass, &mut zoom); + app.canvas.zoom_tool = Some(zoom); + response + } else { + app.canvas.zoom_tool = None; + let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options)); + hand.options = options; + let response = host_run(app, ui, pass, &mut hand); + app.canvas.hand = Some(hand); + response + }; if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) { crate::shortcuts::note_tool_use(app); } - app.canvas.hand = Some(hand); response } else { app.canvas.hand = None; + app.canvas.zoom_tool = None; let mut tool = SessionTool::new(app, view_info, ui); let response = host_run_session(&mut tool, ui, pass); drop(tool); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index d32ec78d67..5a712b5f33 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -5,6 +5,7 @@ use std::cell::RefCell; use craft::behavior::IconId; use craft::menu::MenuBarUi; +use craft::theme::ControlSize; use craft::ui::buttons::{Button, IconButton, ToggleButton}; use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer}; use craft::ui::display::Picture; @@ -101,8 +102,9 @@ fn leading(ui: &mut Ui, app: &mut VectorcraftApp) { } let mut home = menus::home_showing(app); let before = home; - // The title bar's Home has no rule after it, as an options bar's `BarHome` does. - ToggleButton::new(tl!("Home"), Bind::bound(&mut home)).icon(IconSpec::svg(IconId::new("home"))).icon_only().show(ui); + // The title bar's Home has no rule after it, as an options bar's `BarHome` does. It is a small control: its square + // and glyph take the small sizes (`size.control.sm`, `size.icon.glyph_sm`). + ToggleButton::new(tl!("Home"), Bind::bound(&mut home)).icon(IconSpec::svg(IconId::new("home"))).icon_only().size(ControlSize::Sm).show(ui); if home != before { app.run("app.home", json!({})).ok(); } diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 4ba5c01293..c9b14eef54 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -158,11 +158,13 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The tab at the top of window `w`'s floating OS window ([`crate::doc_windows`]): a strip with the -/// window's tab, without its ×. Dragged onto the main strip it docks there ([`doc_tabs`]); the -/// window moves by its title bar, so a tear-off is ignored. → the strip's response. -pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> egui::Response { - let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default()).closable(false)]; - DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs).show(ui).response +/// window's tab and its ×, as the tab has under the main strip. Dragged onto the main strip it +/// docks there ([`doc_tabs`]); the window moves by its title bar, so a tear-off is ignored. → +/// whether the tab's × or a middle click asked to close the window. +pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> bool { + let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default())]; + let strip = DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs); + strip.show(ui).events.into_iter().any(|event| matches!(event, DocumentTabsEvent::CloseRequested(x) if x == w)) } /// Makes document `i` the current one, as a click on its tab does: the Home screen closes, and diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 67cc29b63f..79d4371f47 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -110,12 +110,18 @@ impl Shown { self.find(label).unwrap_or_else(|| panic!("no {label:?} in {:?}", self.names())) } - /// The first node of the latest frame whose name starts with `prefix`, a control before a label. - fn starting(&self, prefix: &str) -> Option { + /// The named control in the window's title bar. The Tools panel can have a control with the same name. + fn app_bar_control(&self, prefix: &str) -> Option { let tree = self.fixture.tree(); - let named: Vec<_> = tree.keys().into_iter().filter(|key| tree.name_of(*key).is_some_and(|name| name.starts_with(prefix))).collect(); - let first = named.iter().find(|key| tree.role_of(**key) != Some(Role::LABEL)).or(named.first()); - first.and_then(|key| self.fixture.target(*key)) + let ctx = self.fixture.ctx(); + let window = ctx.content_rect(); + let title_height = craft::ui::runtime::env::Env::of_root(ctx).tokens.size.bar.title; + let title_bar = egui::Rect::from_min_size(window.min, egui::vec2(window.width(), title_height)); + tree.keys() + .into_iter() + .filter(|key| tree.role_of(*key) != Some(Role::LABEL) && tree.name_of(*key).is_some_and(|name| name.starts_with(prefix))) + .filter_map(|key| self.fixture.target(key)) + .find(|target| title_bar.contains(target.rect.center())) } /// The names the latest frame gives screen readers. @@ -452,7 +458,7 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { for width in (30..=160).rev().map(|w| w as f32 * 10.0) { bar.room(egui::vec2(width, 600.0)); bar.frame(Vec::new()).frame(Vec::new()); - let shown: Vec> = controls.iter().map(|c| bar.starting(c)).collect(); + let shown: Vec> = controls.iter().map(|c| bar.app_bar_control(c)).collect(); for (control, target) in controls.iter().zip(&shown) { if let Some(t) = target { assert!(t.rect.left() >= 0.0 && t.rect.right() <= width, "{width}: {control} at {:?} lies inside the window", t.rect); @@ -541,13 +547,41 @@ fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() { bar.frame(Vec::new()).frame(Vec::new()); assert!(gap.get() > 0.0, "the item gap is read from the theme"); let controls = ["Discord", "Search commands", "Choose a workspace"]; - let rects: Vec = controls.iter().map(|c| bar.starting(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect(); + let rects: Vec = controls.iter().map(|c| bar.app_bar_control(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect(); for pair in rects.windows(2) { let between = pair[1].left() - pair[0].right(); assert!(between >= gap.get() - 0.5, "neighboring controls {pair:?} are {between} apart, under the item gap {}", gap.get()); } } +/// The app bar's Home is a small control (`size.control.sm` high), and each menu title keeps `space.pad.control` +/// between its text and the edges of its highlight. +#[test] +fn the_app_bar_home_is_small_and_menu_titles_pad_their_text() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let read = Rc::new(std::cell::Cell::new((0.0_f32, 0.0_f32))); + let set = Rc::clone(&read); + let mut bar = Shown::new(app, egui::vec2(1600.0, 600.0), move |app, ui| { + let tokens = &craft::ui::runtime::env::Env::of(ui).tokens; + set.set((tokens.size.control.sm, tokens.space.pad.control)); + app.ui(ui); + }); + bar.frame(Vec::new()).frame(Vec::new()); + let (small, pad) = read.get(); + assert!(small > 0.0 && pad > 0.0, "the sizes are read from the theme"); + let home = bar.app_bar_control("Home").unwrap_or_else(|| panic!("Home shows in {:?}", bar.names())).rect; + assert!(home.height() <= small + 0.5, "Home is {} high, over the small control height {small}", home.height()); + let texts = bar.texts(); + for title in ["File", "Edit", "Object"] { + let rect = bar.find(title).unwrap_or_else(|| panic!("{title} shows in {:?}", bar.names())).rect; + let text = + texts.iter().find(|t| t.text == title && rect.contains(t.bounds.center())).unwrap_or_else(|| panic!("{title}'s text in {texts:?}")); + let (left, right) = (text.bounds.left() - rect.left(), rect.right() - text.bounds.right()); + assert!(left >= pad - 0.5 && right >= pad - 0.5, "{title}'s text is {left} and {right} from its edges, under {pad}"); + } +} + /// A text the status bar painted, with where it lies. #[derive(Debug)] struct StatusText { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c0c6bd0bc6..7495e0ed02 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,7 +18,8 @@ //! - `ui.find`: the controls of the window's access tree that match a name or role //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` //! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by -//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`) +//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by +//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the //! PNG comes back in the reply) //! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly @@ -152,6 +153,10 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. + if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { + open.insert(0, strip); + } json!({ "scriptRunning": app.session.script_running(), "scriptReport": app.session.shown_script_report(), @@ -1437,6 +1442,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if crate::prefs_dialog::is_open(app) && (p["dialog"] == "preferences" || (top && dialogs.with(|host| host.stack().is_empty()))) { return wrap(preferences_method(app, method, p)); } + // The Simplify and Smooth sliders are the app's own strip over the canvas, not hosted dialogs: they take a + // request that names them, or the top dialog while no hosted dialog is open. + let hosted_open = dialogs.with(|host| !host.stack().is_empty()); + if let Some(r) = crate::dialogs::simplify_slider::dialog_method(app, method, p, hosted_open) { + return wrap(r); + } // The dialog asked for is `dialog`, the top one when it is missing. let mut params = if p.is_object() { p.clone() } else { json!({}) }; if params.get("dialog").is_none_or(Value::is_null) { diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 2f9c594ab7..b120d35c4a 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -89,6 +89,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::DirectAnchorSelected => tool("cursor-direct-anchor-selected", TIP, None), Cursor::ReshapeSegment => tool("cursor-reshape-segment", TIP, None), Cursor::GroupSelection => badged(CursorBadge::Add), + Cursor::SelectionMove => badged(CursorBadge::Move), Cursor::SelectionCopy => badged(CursorBadge::Copy), Cursor::Move => system(CursorIcon::Move), Cursor::Crosshair => PaintedCursor::Crosshair.into(), @@ -195,7 +196,7 @@ pub(crate) fn request_busy(app: &crate::VectorcraftApp, ctx: &egui::Context) { /// Every cursor with a look: its own, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 99] = [ +const GLYPHS: [Cursor; 100] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -207,6 +208,7 @@ const GLYPHS: [Cursor; 99] = [ Cursor::ReshapeSegment, Cursor::GroupSelection, Cursor::SelectionCopy, + Cursor::SelectionMove, Cursor::Move, Cursor::Crosshair, Cursor::ResizeH, diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 183bda8b47..f4c1d52986 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -1,15 +1,5 @@ use super::*; -/// A hotspot is data a typo moves off the glyph: every painted tool cursor's lies in its icon's box. -#[test] -fn every_tool_cursors_hotspot_lies_inside_its_icon_box() { - for c in GLYPHS { - if let cb::Cursor::Painted(PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) { - assert!((0.0..=24.0).contains(&hotspot.x) && (0.0..=24.0).contains(&hotspot.y), "{c:?}: {hotspot:?}"); - } - } -} - /// A click lands where the glyph points: in every painted tool cursor's image, the icon's own /// mark color (not only its halo) covers the hotspot pixel or one next to it. #[test] @@ -17,7 +7,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { use craft::ui::primitives::{painted_image, register_app_icons}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); register_app_icons(&CURSOR_ICONS); let mut missed = Vec::new(); crate::testing::ui_context() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0e5e2100ba..eee24e9a47 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -148,6 +148,7 @@ pub mod slices; pub mod smart_punctuation; pub(crate) mod smooth_slider; pub mod spot_colors; +pub mod step_repeat; pub mod svg_filter; pub(crate) mod svg_options; pub mod swatch_conflict; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index b712b589d9..402a2b1922 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { let name = "10 pt. Oval"; app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); + let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width; ask(&mut app, json!({"name": name}), true); answer::(&mut app, choice, pump); assert_eq!(open_question(&app), None); assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some())); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name)); - assert!(stroke.width > 0.0); + assert_eq!(stroke.width, width, "the stroke keeps its width"); } } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 8c64b06a80..110c124717 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -437,8 +437,8 @@ mod tests { confirm(&mut app, &ctx); assert!(!app.session.in_interaction()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); - let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0]; - assert!(lighter > 0.6, "{lighter}"); + // #808080 holds less than 50% black, so taking 50% away leaves none. + assert_eq!(fill_hex(&app, id), "#ffffff"); } #[test] diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6d8741d342..6be16732f6 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -349,8 +349,7 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add -/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools' bounding shapes (Add Bounding Rectangle… and Add Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(command: &str, opening: &Map) -> bool { match command { "object.repeat.options" => opening.contains_key("gridType"), @@ -361,7 +360,6 @@ fn previews(command: &str, opening: &Map) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS | crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, @@ -465,7 +463,6 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], - crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], @@ -484,7 +481,6 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), - (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), ("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS), diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 06fa47f045..057eac94eb 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -350,9 +350,14 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map // Free Distort's Reset puts the corners back on the box, wherever they were when it opened. let reset_to = (id == super::free_distort::FREE_DISTORT) .then(|| form::fields_of(&rows, &Map::from_iter([("corners".to_string(), json!(super::free_distort::IDENTITY))]))); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, "effect", fields, move |f| { let rows = effect_params(&cx, f); let dialog = ParamDialog::new("effect", title.clone(), rows).values(Bind::bound(f)).previews(true); + let dialog = match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + }; let dialog = match &reset_to { Some(target) => dialog.reset_to(target.clone()), None => dialog, diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 5b2ee66107..e9e05185b5 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -17,7 +17,8 @@ use std::sync::Arc; use craft::behavior::IconId; use craft::color_ui::ui::{ - ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette, + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, PickedColor, + SwatchPalette, }; use craft::theme::Srgba; use craft::theme::variant::Tone; @@ -43,6 +44,7 @@ use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; use crate::VectorcraftApp; +use crate::panels::color::model_values; use crate::panels::gradient::{edit_point, edits_points, set_stops, set_stops_keeping_models, shown_points}; use crate::panels::{Live, active_paint, c32}; @@ -470,6 +472,9 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi filed.panels.push( ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2]) .layout(ColorPanelLayout::FillStroke) + // The rows show and edit the stop's own values (CMYK %, working RGB), not values + // derived again from its sRGB on every frame. + .edited(Some(PickedColor::in_model(feed.current, model_values(&feed.color)))) .shown(feed.shown.clone()) .show(ui), ); @@ -575,13 +580,11 @@ fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 { } } -/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. -fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { - let Some(dialogs) = app.dialogs() else { return }; - let Some(anchor) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.anchor)) else { return }; +/// `target`'s values, the document's swatches and what the Color panel shows, for the popover's body. +fn feed(app: &VectorcraftApp, target: &Target) -> Feed { let shown = crate::panels::color::shown(app, &crate::panels::color::target_now(app)); let swatches = swatch_colors(app); - let feed = Feed { + Feed { point: matches!(target, Target::Point(..)), color: target.color(), current: Srgba::from(c32(&target.color())), @@ -590,7 +593,14 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(), swatches, shown, - }; + } +} + +/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. +fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(anchor) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.anchor)) else { return }; + let feed = feed(app, target); let at = place(app, ctx, anchor); dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { @@ -776,7 +786,14 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { #[cfg(test)] mod tests { use craft::behavior::{EditEvent, GestureId, Mixed}; - use craft::color_ui::ui::{PanelTarget, PickedColor}; + use std::cell::RefCell; + use std::rc::Rc; + + use craft::color_ui::ui::PanelTarget; + use craft::ui::runtime::access::Role; + use craft::ui::testing::Fixture; + use craft::ui::testing::focus::AccessActionKind; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -1203,4 +1220,65 @@ mod tests { host::pump(&mut app, &ctx); assert!(!is_open(&app)); } + + /// The popover's body over `app`'s selected stop in `mode`, drawn headless; each frame's Color panel output is + /// applied to the stop as `pump` applies it. + fn panel_body(app: Rc>, mode: ColorPanelMode) -> Fixture { + let mut tab = Tab::Color; + let mut panel = ColorPanelState::default(); + panel.mode = mode; + app.borrow_mut().ui.color_panel.mode = mode; + let mut fx = Fixture::new(move |ui| { + let mut app = app.borrow_mut(); + let Some(target) = selected(&app) else { return }; + let feed = feed(&app, &target); + let mut filed = Filed::default(); + body(ui, &feed, &mut tab, &mut panel, &mut filed); + for output in &filed.panels { + crate::panels::color::apply_output(&mut app, output); + } + }); + fx.room(vec2(320.0, 640.0)).settle(); + fx + } + + fn stop_cmyk(app: &VectorcraftApp) -> [f32; 4] { + let Color::Cmyk { c, m, y, k } = stops(app)[1].color else { panic!("a CMYK stop: {:?}", stops(app)[1].color) }; + [c, m, y, k] + } + + /// A CMYK value typed or set on one row of the popover changes only that channel: the others keep their + /// exact values instead of being worked out again from the stop's RGB. + #[test] + fn a_cmyk_stop_keeps_its_other_channels_when_one_is_typed_or_dragged() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let stops_json = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": {"c": 10, "m": 20, "y": 30, "k": 5}}, {"offset": 1, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops_json, "start": [100, 150], "end": [200, 150]}, "keepModel": true})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); + assert!(close(stop_cmyk(&app), [0.10, 0.20, 0.30, 0.05]), "{:?}", stop_cmyk(&app)); + let app = Rc::new(RefCell::new(app)); + let mut fx = panel_body(app.clone(), ColorPanelMode::CmykSliders); + let row = |fx: &Fixture, name: &str| { + fx.by_role(Role::SLIDER).into_iter().find(|t| fx.tree().name_of(t.node) == Some(name)).unwrap_or_else(|| panic!("the {name} slider")) + }; + // Typed: the Cyan field gets 40. + let field = fx.by_role(Role::SPIN_BUTTON).into_iter().find(|t| fx.tree().name_of(t.node) == Some("Cyan")).expect("the Cyan field"); + fx.click(&field).key(Key::A, Modifiers::COMMAND).type_text("40").key(Key::Enter, Modifiers::NONE).settle(); + let typed = stop_cmyk(&app.borrow()); + assert!(close(typed, [0.40, 0.20, 0.30, 0.05]), "typed Cyan: {typed:?}"); + // Set as a screen reader sets it: the Magenta slider goes to 60. + let magenta = row(&fx, "Magenta"); + fx.access(AccessActionKind::SetValue(60.0), &magenta).idle(2); + let set = stop_cmyk(&app.borrow()); + assert!(close(set, [0.40, 0.60, 0.30, 0.05]), "Magenta set to 60: {set:?}"); + // Dragged with the pointer: the Yellow slider's thumb goes from a tenth to most of the way across. + let yellow = row(&fx, "Yellow"); + let along = |f: f32| egui::pos2(yellow.rect.left() + f * yellow.rect.width(), yellow.rect.center().y); + fx.drag_at(along(0.1), along(0.8) - along(0.1)).idle(2); + let [c, m, y, k] = stop_cmyk(&app.borrow()); + assert!(close([c, m, k, 0.0], [0.40, 0.60, 0.05, 0.0]), "dragged Yellow kept the other channels: {:?}", [c, m, y, k]); + assert!(y > 0.5, "the drag moved Yellow: {y}"); + } } diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 98a8515c16..ebc54223f6 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -47,7 +47,15 @@ pub(super) fn options>(list: &[(I, &str)]) -> Vec<(String, Label)> /// Vector Halftone adds Keep Original. The Color row depends on two values, so the rows are built /// from `fields`. pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { - let shapes = [("circle", "Circle"), ("ellipse", "Ellipse"), ("square", "Square"), ("diamond", "Diamond"), ("line", "Line")]; + let shapes = [ + ("circle", "Circle"), + ("ellipse", "Ellipse"), + ("square", "Square"), + ("diamond", "Diamond"), + ("line", "Line"), + ("euclidean", "Euclidean"), + ("elliptical", "Elliptical"), + ]; let mut rows = vec![ Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index f539897c25..8bf7e37874 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -114,11 +114,19 @@ pub(super) fn render_preview( app: &mut VectorcraftApp, ctx: &egui::Context, doc: &vectorcraft_engine::doc::Document, +) -> Option> { + render_page_preview(&mut app.canvas.renderer, ctx.pixels_per_point(), doc) +} + +fn render_page_preview( + renderer: &mut vectorcraft_render::Renderer, + pixels_per_point: f32, + doc: &vectorcraft_engine::doc::Document, ) -> Option> { let region = doc.artboards.first()?.rect; - let px = PREVIEW_PX * ctx.pixels_per_point() as f64; + let px = PREVIEW_PX * pixels_per_point as f64; let scale = px / region.width().max(region.height()).max(1.0); - let img = app.canvas.renderer.render_region(doc, region, scale, true); + let img = renderer.render_region(doc, region, scale, true); Some(Arc::new(crate::canvas::color_image(&img))) } @@ -286,6 +294,8 @@ pub(super) struct ImportPdfDialog { /// The preview shown for a (page, crop, text) revision; `None` for a page that could not be read, which is /// not asked for again. preview: Option<(Revision, Option>)>, + /// One preview at a time. Page changes coalesce while the worker finishes. + pending_preview: Option<(Revision, std::sync::mpsc::Receiver>>)>, /// Why the last password did not open the file. password_error: Option, /// The OK the pump has not answered. @@ -294,7 +304,7 @@ pub(super) struct ImportPdfDialog { impl ImportPdfDialog { fn new(s: State) -> Self { - ImportPdfDialog { id: dialog_id(KIND), s, preview: None, password_error: None, held: HeldAnswer::new() } + ImportPdfDialog { id: dialog_id(KIND), s, preview: None, pending_preview: None, password_error: None, held: HeldAnswer::new() } } /// The preview to render next: the revision of the shown page, crop and text, when the stored one differs. @@ -700,7 +710,14 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> { if s.links_on() { p["linkPages"] = json!(true); } - io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ()) + if crate::opening::available() + && let Some(path) = s.path.as_deref() + { + crate::opening::start_with(app, path, s.file.bytes.clone(), p); + Ok(()) + } else { + io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ()) + } }; // Asked only for the password, the dialog showed no Text choice to keep; the choice for a `.ai` // or `.ait` file is not kept for PDFs. @@ -711,10 +728,10 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> { } /// The preview of the page and boxes `s` shows; `None` for a page that can't be read. -fn preview_image(app: &mut VectorcraftApp, ctx: &egui::Context, s: &State) -> Option> { +fn preview_image(renderer: &mut vectorcraft_render::Renderer, pixels_per_point: f32, s: &State) -> Option> { let opts = fileio::LoadOptions { crop: s.crop, password: s.password(), text_as: s.preview_text_as(), ..Default::default() }; let (doc, _) = fileio::page_document(&s.file.bytes, s.page().saturating_sub(1), &opts).ok()?; - render_preview(app, ctx, &doc) + render_page_preview(renderer, pixels_per_point, &doc) } /// The host pump: judges the OK the dialog holds (opening or placing the file; a refusal keeps the dialog open with @@ -730,10 +747,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { dialog.answer_ok(answer); } }); + return; } - let wanted = dialogs.with(|host| host.get::().and_then(|d| Some((d.wanted_preview()?, d.s.clone())))); - if let Some((revision, s)) = wanted { - let image = preview_image(app, ctx, &s); + let wanted = dialogs.with(|host| { + let dialog = host.get_mut::()?; + if let Some((revision, pending)) = &dialog.pending_preview { + let image = match pending.try_recv() { + Ok(image) => image, + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + }; + if dialog.wanted_preview() == Some(*revision) { + dialog.set_preview(*revision, image); + } + dialog.pending_preview = None; + } + Some((dialog.wanted_preview()?, dialog.s.clone())) + }); + let Some((revision, state)) = wanted else { return }; + let pixels_per_point = ctx.pixels_per_point(); + if crate::opening::available() { + let (sender, pending) = std::sync::mpsc::channel(); + dialogs.with(|host| { + if let Some(dialog) = host.get_mut::() { + dialog.pending_preview = Some((revision, pending)); + } + }); + let wake = ctx.clone(); + let scope = vectorcraft_engine::file_access::ScopeHandle::capture(); + app.jobs().spawn( + "vectorcraft-pdf-preview", + Box::new(move || { + let image = scope.run(|| preview_image(&mut vectorcraft_render::Renderer::new(), pixels_per_point, &state)); + let _ = sender.send(image); + wake.request_repaint(); + }), + ); + } else { + let image = preview_image(&mut app.canvas.renderer, pixels_per_point, &state); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { dialog.set_preview(revision, image); diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index fb0ad99911..0553775449 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -1185,4 +1185,20 @@ mod tests { ok(&mut app); assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); } + + /// `ui.layerOptions` and `ui.newLayer` open the dialog whose `key` their params text names, as `ui.inspect` + /// lists it. + #[test] + fn layer_options_params_text_names_the_dialog_key_ui_inspect_lists() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + let mut app = app(); + app.run(command, arguments).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{command} opens `{key}`, which its params text does not name"); + } + } } diff --git a/crates/ui-egui/src/dialogs/layers_panel_options.rs b/crates/ui-egui/src/dialogs/layers_panel_options.rs index 290641848d..0771d6ca38 100644 --- a/crates/ui-egui/src/dialogs/layers_panel_options.rs +++ b/crates/ui-egui/src/dialogs/layers_panel_options.rs @@ -127,4 +127,17 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap(); assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it"); } + + /// `ui.layersPanelOptions` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == CMD).expect("registered").3; + let mut app = app(); + app.run(CMD, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{CMD} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index 388ded4a68..69e5e0ceed 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -198,7 +198,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Ok(done)) => Some(done["gaps"].clone()), Some(Err(e)) => { app.status(e); - None + // The failed preview rolled the groups back, so the gaps an earlier one found are gone too. + Some(Value::Null) } None => None, }; @@ -519,6 +520,23 @@ mod tests { assert!(!drawn(&mut app), "no preview, no gap"); } + /// A preview that fails after one that found gaps leaves no gaps drawn from the earlier one. + #[test] + fn a_failed_preview_draws_no_earlier_gaps() { + let mut app = app(); + gapped_group(&mut app); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert_eq!(overlays(&app).len(), 1, "the gap is previewed"); + // A custom size past 72 pt is refused, and the preview with it fails. + set(&app, "size", json!("custom")).unwrap(); + set(&app, "custom", json!(100.0)).unwrap(); + pump_all(&mut app); + assert!(overlays(&app).is_empty(), "{:?}", overlays(&app)); + } + /// With Preview on, a Gap Preview Color with an alpha part is not previewed: the group keeps /// its own color, the gaps draw in black, OK refuses the color and Cancel rolls the preview back. #[test] diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3639dbf49..b37a541ac8 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -208,4 +208,18 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them"); } + + /// `ui.navigatorPanelOptions` without options opens the dialog whose `key` its params text names, as `ui.inspect` + /// lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == KEY).expect("registered").3; + let mut app = app(); + app.run(KEY, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{KEY} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 56d6a29a35..6b2f799265 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -18,7 +18,7 @@ use serde::de::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; -use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; +use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI}; use craft::behavior::{ColumnWidth, IconId}; use craft::ui::buttons::Button; @@ -155,8 +155,8 @@ impl<'de> Deserialize<'de> for VcNewDocument { pub(crate) struct Setup { /// The name of the next untitled document. untitled: String, - /// The New Document profiles, each with whether it was edited. - profiles: Vec<(&'static str, bool)>, + /// The New Document profiles, each with what is at its file. + profiles: Vec<(&'static str, ProfileFile)>, /// Whether profiles can be edited (the web build and runs without preferences have no folder). has_profile_folder: bool, /// Numbers Without Units Are Points. @@ -168,7 +168,7 @@ impl Setup { fn of(app: &VectorcraftApp) -> Self { Self { untitled: app.session.peek_untitled().to_string(), - profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_customized(name))).collect(), + profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_file(name))).collect(), has_profile_folder: app.session.new_doc_profile_dir().is_some(), bare_points: app.session.prefs.numbers_without_units_are_points, } @@ -352,11 +352,11 @@ impl DocumentSettings for VcNewDocument { Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); - // The two buttons across the column, one above the other. + // The two buttons side by side, each as wide as its words. let (mut more, mut manage) = (None, None); - Stack::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { - more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").sizing(Sizing::FillWidth).show(ui)); - manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").sizing(Sizing::FillWidth).show(ui)); + Row::new().gap(Gap::Item).show(ui, |ui, _| { + more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").sizing(Sizing::Content).show(ui)); + manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").sizing(Sizing::Content).show(ui)); }); if let Some(more) = &more { let mut more_open = memory.more_open != clicked(more); @@ -618,12 +618,22 @@ fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); // The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up. Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| { - for (name, customized) in &setup.profiles { - Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui); - if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) { + for (name, file) in &setup.profiles { + // A link or a folder in the profile's place is not read: its name is dimmed and says why, Edit + // is off, and Reset removes a link but not a folder. + let unusable = matches!(file, ProfileFile::NotPlain | ProfileFile::Folder); + let mut shown = Text::new(text(tl!(name))).id_salt(("profile", name)); + if unusable { + let why = tl!("The profile's file is a link or a folder, so new documents get the default settings"); + shown = shown.shade(Shade::Muted).tooltip(text(why)); + } + shown.show(ui); + let edit = Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder && !unusable); + if clicked(&edit.show(ui)) { *action = Some(format!("{EDIT_PROFILE}:{name}")); } - if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) { + let reset = Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(file.resettable()); + if clicked(&reset.show(ui)) { *action = Some(format!("{RESET_PROFILE}:{name}")); } } @@ -1132,35 +1142,35 @@ mod tests { // The resting appearance is measured after dialog and tile state transitions have settled. let out = laid_out_after(&mut app, egui::vec2(1280.0, 900.0), 15); let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); - // Print opens on Letter. Inspect the A4 preset, away from the initial focus and the selected preset. - let card = nodes + // The Home screen's own document cards stand behind the dialog, and the update lists nodes in no fixed order: + // the card is looked for under the dialog only. + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut in_dialog = Vec::new(); + let mut stack: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Dialog).map(|(id, _)| *id).collect(); + while let Some(id) = stack.pop() { + if let Some(node) = by_id.get(&id) { + in_dialog.push(*node); + stack.extend(node.children().iter().copied()); + } + } + let cards: Vec<_> = in_dialog .iter() - .find(|(_, n)| { - n.role() == egui::accesskit::Role::ListItem - && n.label().is_some_and(|name| name.split(',').next() == Some("A4")) - && n.is_selected() == Some(false) - }) - .and_then(|(_, n)| n.bounds()) + .filter(|n| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false)) + .filter_map(|n| n.bounds()) .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) - .unwrap_or_else(|| { - panic!( - "no unselected A4 among the presets: {:?}", - nodes - .iter() - .filter(|(_, n)| n.role() == egui::accesskit::Role::ListItem) - .map(|(_, n)| (n.label(), n.is_selected())) - .collect::>() - ) - }); + .collect(); + assert!(!cards.is_empty(), "a preset card that is not selected"); let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes); let rects: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); let veil = |fill: egui::Color32| fill.a() > 0 && fill.a() < scrim.a() && fill.to_opaque() == scrim.to_opaque(); - assert!( - rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)), - "a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}", - rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::>() - ); - assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile"); + for card in cards { + assert!( + rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)), + "a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}", + rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::>() + ); + assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile"); + } } /// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and @@ -1243,6 +1253,60 @@ mod tests { } } + /// The rows of Preset Details stand at least the framework's stack gap apart: the Height caption sits that far + /// below the Width field, and the Top bleed field that far below Height. Before, the rows were a tight gap apart + /// and each caption touched the field above it. + #[test] + fn preset_details_rows_stand_a_stack_gap_apart() { + use craft::ui::contract::Gap; + let mut stack = 0.0; + let mut theme = crate::testing::ui_context().run_ui(Default::default(), |ui| stack = Gap::Stack.points(ui)); + theme.textures_delta.clear(); + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let captions: Vec<(String, egui::Rect)> = crate::tests_labels::text_shapes(&out) + .into_iter() + .map(|(t, transform)| (t.galley.text().to_string(), transform * t.visual_bounding_rect())) + .collect(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let field = |label: &str| { + let (_, n) = nodes + .iter() + .find(|(_, n)| n.label() == Some(label) && n.role() == egui::accesskit::Role::SpinButton) + .unwrap_or_else(|| panic!("no field {label}")); + n.bounds().expect("bounds") + }; + let (width, height, top) = (field("Width"), field("Height"), field("Top")); + let caption_below = |text: &str, y: f64| { + captions.iter().filter(|(t, r)| t == text && f64::from(r.top()) >= y - 1.0).map(|(_, r)| f64::from(r.top())).fold(f64::INFINITY, f64::min) + }; + let height_caption = caption_below("Height", width.y1); + assert!(height_caption.is_finite(), "no Height caption stands below the Width field {width:?}"); + let gap = height_caption - width.y1; + assert!(gap + 0.5 >= f64::from(stack), "the Height caption stands {gap} below Width, at least the stack gap {stack}"); + let bleed_caption = caption_below("Bleed", height.y1); + assert!(bleed_caption < top.y0, "Bleed's caption {bleed_caption} stands above its Top field {top:?}"); + let gap = bleed_caption - height.y1; + assert!(gap + 0.5 >= f64::from(stack), "the Bleed caption stands {gap} below Height, at least the stack gap {stack}"); + } + + /// More Settings and Manage Profiles stand side by side, each as wide as its words, not across the whole column. + #[test] + fn more_settings_and_manage_profiles_stand_in_a_row() { + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: &str, role: egui::accesskit::Role| { + let (_, n) = nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} {label}")); + n.bounds().expect("bounds") + }; + let more = bounds("More Settings", egui::accesskit::Role::Button); + let manage = bounds("Manage Profiles", egui::accesskit::Role::Button); + assert!(more.x1 <= manage.x0 && (more.y0 - manage.y0).abs() < 1.0, "Manage Profiles {manage:?} follows More Settings {more:?} on its line"); + } + /// More Settings edits only the artboard layout, spacing and columns, and creates nothing. #[test] fn more_settings_is_a_popup_holding_only_the_artboard_layout() { @@ -1312,7 +1376,8 @@ mod tests { let mut app = app(); open(&mut app); set(&app, "artboards", json!(5)).unwrap(); - set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); + assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err(), "a fraction is refused"); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); create(&mut app); let st = app.session.active().unwrap(); @@ -1432,11 +1497,11 @@ mod tests { let setup = Setup::of(&app); assert!(setup.has_profile_folder); assert_eq!(setup.profiles.len(), newdoc::profile_names().count()); - assert!(setup.profiles.iter().all(|(_, customized)| !customized)); + assert!(setup.profiles.iter().all(|(_, file)| *file == ProfileFile::None)); assert!(profile_action(&mut app, "profile.edit:Print"), "Edit closes the dialog"); assert_eq!(app.session.active().unwrap().doc.title, "Print"); assert!(dir.join("Print.vectorcraft").is_file()); - assert!(Setup::of(&app).profiles.iter().any(|(name, customized)| *name == "Print" && *customized)); + assert!(Setup::of(&app).profiles.iter().any(|(name, file)| *name == "Print" && *file == ProfileFile::Plain)); assert!(!profile_action(&mut app, "profile.reset:Print"), "Reset leaves the dialog open"); assert!(!dir.join("Print.vectorcraft").exists()); let _ = std::fs::remove_dir_all(&dir); @@ -1606,8 +1671,8 @@ mod tests { } } - /// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side under them, and - /// the Bleed fields form two rows of two, Top and Bottom above Left and Right, with the link button after Right; + /// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side, and the Bleed + /// fields stand in one row, or in two rows of two when the column is narrow, with the link button after Right; /// before, at 800 by 600 Orientation's buttons stood one above the other between Height and Artboards. #[test] fn new_document_details_stay_in_rows_in_small_windows() { @@ -1622,11 +1687,11 @@ mod tests { assert!(h.y0 == a.y0 && h.x1 <= a.x0, "{at}: Height {h:?} and Artboards {a:?} share a row"); assert!(a.y1 <= portrait.y0 || landscape.x1 <= a.x0, "{at}: Orientation {landscape:?} stays clear of Artboards {a:?}"); let [top, bottom, left, right] = ["Top", "Bottom", "Left", "Right"].map(|side| node(&nodes, side, Role::SpinButton)); - assert!(top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0, "{at}: two Bleed rows: {top:?} {bottom:?} {left:?} {right:?}"); - assert!( - top.x0 == left.x0 && bottom.x0 == right.x0 && top.x1 <= bottom.x0, - "{at}: two Bleed columns: {top:?} {bottom:?} {left:?} {right:?}" - ); + // A column wide enough holds the four fields in one row; a narrower one, in two rows of two. + let one_row = [bottom, left, right].iter().all(|f| f.y0 == top.y0) && top.x1 <= bottom.x0 && bottom.x1 <= left.x0 && left.x1 <= right.x0; + let two_rows = top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0 && top.x0 == left.x0 && bottom.x0 == right.x0; + let two_rows = two_rows && top.x1 <= bottom.x0 && left.x1 <= right.x0; + assert!(one_row || two_rows, "{at}: the Bleed fields stand in one row or two: {top:?} {bottom:?} {left:?} {right:?}"); let link = node(&nodes, "Make all settings the same", Role::Button); assert!(right.x1 <= link.x0 && link.x1 <= dialog.x1, "{at}: the link button {link:?} follows Right {right:?} inside {dialog:?}"); } diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index 465fdcb850..ee0867d0dd 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,7 +4,8 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, transform, transform_each, width_point, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, transform_each, + width_point, }; use crate::VectorcraftApp; @@ -15,6 +16,8 @@ pub(crate) struct ObjectDialogs { pub transform: Option, /// The open Transform Each dialog's preview record. pub each: Option, + /// The open Step and Repeat dialog's preview record. + pub step: Option, /// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records. pub path: Vec, /// The open Split Into Grid dialog's record. @@ -46,6 +49,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { sync(app); transform::pump(app, ctx); transform_each::pump(app, ctx); + step_repeat::pump(app, ctx); path_ops::pump(app, ctx); shapes::pump(app, ctx); flare_options::pump(app, ctx); @@ -73,6 +77,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> bool { } match id { "object.transformEach" => transform_each::open(app), + step_repeat::CMD => step_repeat::open(app), "path.average" => path_ops::open(app, PathOp::Average), "path.averageJoin" => path_ops::open(app, PathOp::AverageJoin), "object.path.offsetPath" => path_ops::open(app, PathOp::OffsetPath), diff --git a/crates/ui-egui/src/dialogs/option_form.rs b/crates/ui-egui/src/dialogs/option_form.rs index fde3f40932..7b1bf40418 100644 --- a/crates/ui-egui/src/dialogs/option_form.rs +++ b/crates/ui-egui/src/dialogs/option_form.rs @@ -631,7 +631,7 @@ pub(super) mod tests { tool: "shapeBuilder", opens_on: vec![ ("openFilledAsClosed", json!(true)), - ("pickColorFrom", json!("artwork")), + ("pickColorFrom", json!("swatches")), ("cursorSwatchPreview", json!(false)), ("selection", json!("freeform")), ("highlightFill", json!(true)), diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index d6f05d0af7..03b4cc19bd 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -3,8 +3,8 @@ //! clipped to them. //! //! Fields: `preserve` (transforms|bounds|fileDimensions|fit|fill), `align` (0-8, row by row from -//! the top left) and `clip`. OK runs `links.placementOptions` with them and `ids` (null: the -//! selected images): one undo step. +//! the top left) and `clip`. OK runs `links.placementOptions` with them and the `ids` the dialog +//! opened on (by default the images selected then): one undo step. // PLAN: assumed craft_ui paths for ParamDialog, ParamKind, Param, DialogFields, FieldValue, HostedParamDialog and Label. use craft::ui::contract::Bind; @@ -48,6 +48,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let source = (active.uid, active.reverts); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; + // The images read: OK applies to these, whatever is selected by then. + let ids = r["ids"].clone(); let placement = &r["placement"]; let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE); let mut fields = DialogFields::from_pairs([ diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 8b6606e068..d7fb438d2c 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -42,7 +42,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use craft::menu::Node; -use craft::ui::contract::Show as _; +use craft::ui::contract::{Bind, Show as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; @@ -548,7 +548,13 @@ pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String /// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is /// shown for the values (`m.visible`), after the description. The rows are made again in the UI /// language when it changes while the dialog is open; the field values stay as they are. -fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static { +fn build( + key: &'static str, + m: Manifest, + all: Arc<[Param]>, + look: Look, + canvas: Option, +) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static { let rows_in = std::sync::Mutex::new((lang(), all)); move |fields| { let all = { @@ -564,7 +570,10 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl rows.push(Param::read_only_text("description", "", look.description.clone()).full_width()); } rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned()); - let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews); + let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews).values(Bind::bound(fields)); + if let Some(canvas) = canvas.filter(|_| look.previews) { + dialog = dialog.canvas(canvas); + } if let Some(ok) = look.ok { dialog = dialog.ok_label(ok.into()); } @@ -592,7 +601,8 @@ fn open_hosted( close_open(app); let all: Arc<[Param]> = form::plugin_params(&m, &values).into(); let fields = form::fields_of(&all, &values); - let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string()); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look, canvas)).instance(instance.to_string()); let id = dialogs.with(|host| host.open(dialog)); Ok((id, all)) } diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2e029fc1c6..f1585adc6b 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -125,6 +125,12 @@ impl LivePreview { Ok(Value::Null) } + /// OK for a selection command: rolls its preview back and runs the command without an interaction. + pub(crate) fn commit_selection(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { + self.cancel(app); + Self::default().commit(app, cmd, params) + } + /// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is. pub(crate) fn cancel(self, app: &mut VectorcraftApp) { if self.previewed.is_some() && self.owns(app) { diff --git a/crates/ui-egui/src/dialogs/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index 6e7f191f8f..be61dbe02b 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -217,4 +217,18 @@ mod tests { assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "the rectangle stays a path"); assert_eq!(st.history.undo.len(), steps + 1); } + + /// `ui.rasterEffectsSettingsDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn settings_dialog_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.rasterEffectsSettingsDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, super::CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 3926501a05..d567dd3363 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -110,7 +110,7 @@ impl RearrangeValues { } /// The length unit a document unit shows as. -fn length_kind(unit: Unit) -> UnitKind { +pub(super) fn length_kind(unit: Unit) -> UnitKind { match unit { Unit::Picas => UnitKind::Picas, Unit::Inches => UnitKind::Inches, diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 16b99491a6..c3fae6fd44 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -114,22 +114,32 @@ fn rows() -> Vec<(&'static str, &'static str, &'static str, Value)> { #[test] fn a_3d_row_sets_its_param_previews_and_applies_in_one_step() { + // One window serves every row: Cancel, and OK followed by Undo, leave the drawing as the dialog found it, and each + // row opens the dialog again over it. + let mut shown: Option = None; for (effect, page, key, value) in rows() { let name = format!("{effect}.{key}"); for confirm in [false, true] { - let mut h = drawn(SQUARE, effect); - let before = source(&h); + let p = json!({"effect": effect, "item": null}); + let h = match shown.as_mut() { + Some(h) => { + reopen(h, p); + h + } + None => shown.insert(opened(app_with(SQUARE), p)), + }; + let before = source(h); h.set("__page", json!(page)); h.set(key, value.clone()); - assert!(same(&stored(&h, effect)[key], &value), "{name}: the preview follows the row"); + assert!(same(&stored(h, effect)[key], &value), "{name}: the preview follows the row"); if confirm { h.ok(); - assert!(same(&stored(&h, effect)[key], &value), "{name}: OK keeps it"); - undo(&h); + assert!(same(&stored(h, effect)[key], &value), "{name}: OK keeps it"); + undo(h); } else { h.cancel(); } - assert_eq!(doc(&h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" }); + assert_eq!(doc(h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" }); } } } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 6c79fb69da..1bf7819ecb 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -898,3 +898,18 @@ fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() { let bytes = fields(&app)["optimizeK"].as_f64().unwrap() * 1024.0; assert!(bytes >= after as f64 && bytes < after as f64 + 2.0, "{bytes} for {after}"); } + +/// `file.saveForWeb` without settings opens the dialog whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "file.saveForWeb"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let dir = vectorcraft_testkit::temp_dir("sfw-dialog-key"); + let (mut app, _) = app(&dir, false); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "save-for-web"); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 091a2d5d97..1dad06f331 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1175,3 +1175,17 @@ fn the_range_bleed_and_subset_fields_are_named() { } } } + +/// `ui.pdfPresetDialog` opens the preset editor whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn preset_editor_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.pdfPresetDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let (mut app, _) = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, PDF_KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index fae58f693d..221807dade 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -497,7 +497,7 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map, presets: &[ let mine = fields.get("settings").and_then(|all| all.get(id)).and_then(Value::as_object).cloned().unwrap_or_default(); let tiny = mine.get("profile").and_then(Value::as_str) == Some("tiny12"); let params = match id { - "svg" => svg_options::svg_params(true, tiny), + "svg" => svg_options::svg_params(svg_options::Mode::Export, true, tiny), "pdf" => Vec::new(), _ => png_options::raster_params(id, true, None), }; diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 9ad62ba03d..22d999782c 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -39,11 +39,24 @@ //! allows are the ones Choose… picked, at most 2,048; no field sets them. Escape, `ui.dialog.cancel` //! and `ui.dialog.confirm` without an `answer` give Deny. Enter allows nothing: both Allow buttons //! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder. +//! +//! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of +//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other +//! dialog is open and no text field or text being typed on the canvas has the keyboard. Its fields +//! are `jobs` (each job's `document`, `printer` and `pages`, read from the jobs when it opens; no +//! field sets them) and `answer`. Only the person at the keyboard prints them, with a click on its +//! Print button or Space once Tab gave it the focus: the button takes no click for +//! [`PRINT_ENABLE_DELAY_SECS`] after the dialog is first drawn, and Enter does not print. +//! `ui.dialog.set` refuses `answer: "print"`, `ui.dialog.confirm` without `answer: "cancel"` is +//! refused, and a click made by automation is refused and the dialog opens again. Cancel, Escape, +//! `ui.dialog.cancel` and `answer: "cancel"` drop the jobs, from anyone; the script's changes stay +//! either way. use std::path::Path; use std::sync::Arc; use craft::host::{PickRequest, Picked}; +use craft::keymap::Key; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _}; @@ -52,6 +65,7 @@ use craft::ui::dialog::{ }; use craft::ui::display::Text; use craft::ui::layout_components::Stack; +use craft::ui::runtime::keys; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; @@ -60,6 +74,7 @@ use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; +use vectorcraft_engine::script::printing::PreparedPrint; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; use super::script_window::{self, ScriptWindow}; @@ -76,6 +91,8 @@ pub const CLOSE_KIND: &str = "scriptClose"; pub const NOTICE_KIND: &str = "scriptDialog"; /// The dialog kind of a script's file dialogs. pub const PICKER_KIND: &str = "scriptFiles"; +/// The dialog kind of the question before the jobs a script prepared for a printer are sent. +pub const PRINT_KIND: &str = "scriptPrint"; /// Why Allow Once and Always Allow are refused to automation. pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; @@ -744,17 +761,21 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { /// Takes the answers of the script's dialogs, once per frame, and gives them to the run. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some((notice, files, run, growth, close)) = with_host(app, |host, _| { + let Some((notice, files, run, growth, close, print)) = with_host(app, |host, _| { ( host.take::(), host.take::(), host.take::(), host.take::(), host.take::(), + host.take::(), ) }) else { return; }; + if let Some(result) = print { + settle_print(app, result); + } if let Some(result) = notice { settle_notice(app, result); } @@ -963,3 +984,157 @@ fn choose(app: &mut VectorcraftApp) { Ok(Value::Null) }); } + +/// How long the print question's Print button takes no click after the dialog is first drawn, in +/// seconds: VectorCraft's own value, so a click or key meant for what was there before does not +/// send a job. +pub(crate) const PRINT_ENABLE_DELAY_SECS: f64 = 1.0; + +/// Opens the question before the jobs a script prepared for a printer are sent, once the run has +/// ended, no other dialog is open and nothing is being typed: while a text field or text on the +/// canvas has the keyboard it waits, and a later poll opens it. +pub(crate) fn ask_print(app: &mut VectorcraftApp) { + if app.session.script_running() || !app.session.script_prints_waiting() || busy(app) { + return; + } + let typing = app.ui_ctx.as_ref().is_some_and(egui::Context::text_edit_focused) || app.session.tool_wants_text(); + if typing { + return; + } + let dialog = ScriptPrint::new(app.session.script_prints()); + with_host(app, |host, _| host.open(dialog)); +} + +/// One job as the print question lists it. +#[derive(Clone)] +struct PrintRow { + document: String, + printer: String, + pages: u64, +} + +/// What the print question answers with: whether Print was clicked. +pub(crate) struct PrintAnswer { + pub(crate) print: bool, +} + +/// The question before the jobs a script prepared for a printer are sent. It lists the jobs as they +/// were when it opened, so no field of the dialog changes what the person reads. +pub(crate) struct ScriptPrint { + jobs: Vec, + /// When the dialog was first drawn, on egui's clock. + shown_at: Option, + answer: Option<&'static str>, +} + +impl ScriptPrint { + fn new(jobs: &[PreparedPrint]) -> Self { + let jobs = jobs.iter().map(|j| PrintRow { document: j.title.clone(), printer: j.printer.clone(), pages: j.sheets }).collect(); + Self { jobs, shown_at: None, answer: None } + } +} + +impl StackDialog for ScriptPrint { + type Result = PrintAnswer; + + fn id(&self) -> DialogId { + dialog_id(PRINT_KIND) + } + + fn key(&self) -> Option<&str> { + Some(PRINT_KIND) + } + + /// Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the dialog was first drawn, and + /// is not the dialog's default: Enter never prints, also on the focused button. + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let now = ui.input(|i| i.time); + // A focused button takes Enter as a click: an Enter held, or pressed in this pass and let go in it too, refuses Print. + let pressed = |e: &egui::Event| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, .. }); + let enter = keys::held(ui.ctx()).contains(&Key::Enter) || ui.input(|i| i.raw.events.iter().any(pressed)); + let wait = (*self.shown_at.get_or_insert(now) + PRINT_ENABLE_DELAY_SECS - now).max(0.0); + if wait > 0.0 { + ui.ctx().request_repaint_after_secs(wait as f32); + } + // Print pressed with Enter is refused and leaves the question open. + let buttons = [ + FooterButton::new(tl!("Print"), DialogRole::Other).enabled(wait <= 0.0).stays_open(enter), + FooterButton::new(tl!("Cancel"), DialogRole::Cancel), + ]; + let jobs = &self.jobs; + let prompt = + Prompt::new(tl!("Print"), tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print.")) + .answers(buttons) + .extras(move |ui| { + egui::ScrollArea::vertical().id_salt("script-print-jobs").max_height(200.0).show(ui, |ui| { + egui::Grid::new("script-print-jobs").num_columns(3).spacing([16.0, 4.0]).show(ui, |ui| { + for head in [tl!("Document"), tl!("Printer"), tl!("Pages")] { + Text::new(head).show(ui); + } + ui.end_row(); + for job in jobs { + Text::new(shown_text(&job.document, false)).show(ui); + Text::new(shown_text(&job.printer, false)).show(ui); + Text::new(job.pages.to_string()).show(ui); + ui.end_row(); + } + }); + }); + }); + match prompt.show(ui).picked? { + 0 if wait <= 0.0 && !enter => Some(DialogResult::Ok(PrintAnswer { print: true })), + 0 => None, + _ => Some(DialogResult::Cancel), + } + } + + /// `ui.dialog.confirm` takes only Cancel. + fn confirm(&mut self, _: &egui::Context) -> Option { + (self.answer == Some("cancel")).then_some(PrintAnswer { print: false }) + } + + fn json_fields(&self) -> Option { + let jobs: Vec = self.jobs.iter().map(|j| json!({"document": j.document, "printer": j.printer, "pages": j.pages})).collect(); + Some(json!({ "jobs": jobs, "answer": self.answer })) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + if field != "answer" { + return Err(FieldRefusal::Unknown.message(field)); + } + self.answer = Some(match value.as_str() { + Some("cancel") => "cancel", + Some("print") => return Err(PRINT_BY_PERSON.into()), + _ => return Err("`answer` for the print question must be one of: print, cancel".into()), + }); + Ok(()) + } +} + +/// Sends the jobs when the person at the keyboard clicked Print; drops them on Cancel, from anyone. +/// Print from a pass automation drove is refused and the question opens again. +pub(crate) fn settle_print(app: &mut VectorcraftApp, result: DialogResult) { + let print = result.ok().is_some_and(|a| a.print); + if print && app.automation_asked() { + app.status(PRINT_BY_PERSON); + ask_print(app); + return; + } + let jobs = app.session.take_script_prints(); + if jobs.is_empty() { + return; + } + if !print { + app.status(PRINTS_DROPPED); + return; + } + // The dialog is closed and the jobs are taken: a failure is reported in the status bar. + if let Err(e) = crate::print::send_script_prints(app, jobs) { + app.status(e); + } +} + +/// Print's refusal when automation asked for it. +pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs"; +/// The status after Cancel. +pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent"; diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index cb58f856a7..2a4f5b0f9c 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -13,11 +13,14 @@ // PLAN: the framework paths below (`craft_ui_widgets`, `craft_ui_contract`, `craft_behavior`) and // `LivePreview`'s module are assumed; no app file imports them yet. +use craft::automation::dialogs::MAX_DIALOG_FIELDS; +use craft::automation::protocol::Params; use craft::behavior::overlay::{Align, Side}; use craft::behavior::{CanvasView, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::overlay::{Anchor, Dismiss, Outside, Place}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::dialog_id; use craft::ui::layout_components::Row; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; @@ -78,6 +81,20 @@ impl StripKind { StripKind::Smooth => SMOOTH_AUTO_LEVEL, } } + + /// The dialog key `ui.inspect` lists the strip under, which `ui.dialog.set`, `ui.dialog.confirm` and + /// `ui.dialog.cancel` take as `dialog`. + pub(crate) fn key(self) -> &'static str { + match self { + StripKind::Simplify => "simplifySlider", + StripKind::Smooth => "smoothSlider", + } + } + + /// The id `ui.inspect` lists the strip under: the one a hosted dialog with the same key has, as a decimal string. + fn id(self) -> String { + dialog_id(self.key()).value().to_string() + } } /// An open slider strip: the level the canvas previews, the selection's bounds from before any @@ -210,6 +227,132 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result { Ok(json!({ "tolerance": tolerance })) } +/// The open strip as `ui.inspect` lists a dialog, `{id, parent, key, fields: {level}}`; `None` when no strip shows. +pub(crate) fn inspected(app: &VectorcraftApp) -> Option { + let strip = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?; + let kind = strip.kind; + Some(json!({ "id": kind.id(), "parent": null, "key": kind.key(), "fields": { "level": strip.level() } })) +} + +/// The level a `ui.dialog.set` on a strip of `kind` asks for: field `level`, a number from 0 to 100, as `field` and +/// `value` or as the last item of `fields`. `None` when it sets nothing. +fn requested_level(kind: StripKind, params: &Value) -> Result, String> { + let level = |field: &Value, value: &Value| { + let field = field.as_str().ok_or("`field` is not a string")?; + if field != "level" { + return Err(format!("the {} slider has no field `{field}`", kind.label())); + } + match value.as_f64() { + Some(level) if (0.0..=100.0).contains(&level) => Ok(level), + _ => Err("`level` must be a number from 0 to 100".to_string()), + } + }; + let Some(list) = params.get("fields") else { + return match params.get("field") { + Some(field) => level(field, params.get("value").unwrap_or(&Value::Null)).map(Some), + None if params.get("value").is_some() => Err("missing `field`".into()), + None => Ok(None), + }; + }; + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".into()); + } + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + let mut last = None; + for item in items { + last = Some(level(item.get("field").unwrap_or(&Value::Null), item.get("value").unwrap_or(&Value::Null))?); + } + Ok(last) +} + +/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`) when `params.dialog` names the open strip: +/// its key or the id [`inspected`] lists, or `"top"` (or no `dialog`) while `hosted_open` is false. `None` for any +/// other dialog. +/// +/// `ui.dialog.set {field: "level", value}` moves the slider and previews the level, then answers with `action` +/// (`confirm` or `cancel`) when one is given; a set it refuses leaves the slider as it was. `ui.dialog.confirm` keeps +/// the preview as one undo step, as Enter does, and `ui.dialog.cancel` puts the paths back, as Escape does. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value, hosted_open: bool) -> Option> { + let kind = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?.kind; + let ours = match params.get("dialog") { + None | Some(Value::Null) => !hosted_open, + Some(Value::String(named)) if named == "top" => !hosted_open, + Some(Value::String(named)) => named == kind.key() || *named == kind.id(), + Some(named) => named.as_u64().is_some_and(|id| id.to_string() == kind.id()), + }; + if !ours { + return None; + } + let keys: &[&str] = match method { + "ui.dialog.set" => &["dialog", "field", "value", "fields", "action"], + "ui.dialog.confirm" | "ui.dialog.cancel" => &["dialog"], + _ => return None, + }; + if let Err(e) = Params(params).only(None, keys) { + return Some(Err(e)); + } + let answer = match (method, params.get("action")) { + ("ui.dialog.confirm", _) => Some(true), + ("ui.dialog.cancel", _) => Some(false), + (_, None | Some(Value::Null)) => None, + (_, Some(action)) if action == "confirm" => Some(true), + (_, Some(action)) if action == "cancel" => Some(false), + (_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())), + }; + let level = if method == "ui.dialog.set" { + match requested_level(kind, params) { + Ok(None) if answer.is_none() => return Some(Err("missing `field`".into())), + Ok(level) => level, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let mut strip = app.object_dialogs.strip.take()?; + if let Some(level) = level { + let before = strip.level; + strip.level = level; + let params = strip.params(); + let ran = strip.preview.run(app, true, kind.label(), kind.cmd(), ¶ms); + // Nothing ran: the canvas already previews this level, or another edit holds the interaction. + let shown = || { + app.session + .active() + .and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()) + .is_some_and(|(cmd, showing)| cmd == kind.cmd() && showing == ¶ms) + }; + let error = match ran { + Some(Err(e)) => Some(e), + None if !shown() => Some(tl!("Finish the active edit first.").to_owned()), + _ => None, + }; + if let Some(e) = error { + strip.level = before; + app.object_dialogs.strip = Some(strip); + return Some(Err(e)); + } + } + app.object_dialogs.strip = Some(strip); + let set = inspected(app).unwrap_or(Value::Null); + let Some(answer) = answer else { return Some(Ok(set)) }; + let strip = app.object_dialogs.strip.take()?; + let result = if answer { + let params = strip.params(); + strip.preview.commit(app, kind.cmd(), params).map(|_| Value::Null) + } else { + strip.cancel(app); + Ok(Value::Null) + }; + // A set with an `action` replies `{dialog, result}`: the slider as the set left it, and the answer's result. + Some(match (method, result) { + ("ui.dialog.set", Ok(result)) => Ok(json!({ "dialog": set, "result": result })), + (_, result) => result, + }) +} + /// Where the strip hangs: a point under the lowest corner on screen of the selection's bounds from /// before the preview, centred on them, kept on the canvas. fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs new file mode 100644 index 0000000000..4a14fe4d2a --- /dev/null +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -0,0 +1,306 @@ +//! Object → Step and Repeat: copies of the selection on a grid or filling a sheet, with the gaps +//! between the cut paths, every other column or row turned by 180° (`object.stepAndRepeat`), +//! previewed live on the canvas. +//! +//! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the +//! artboard), `rotate` (`none`, `columns` or `rows`), `cutId` (an object of the selection, or +//! empty for the selection itself). + +use craft::ui::contract::Bind; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use serde_json::{Map, Value, json}; + +use super::host::{HeldOptions, open_held_with}; +use super::preview::LivePreview; +use crate::VectorcraftApp; + +pub(crate) const CMD: &str = "object.stepAndRepeat"; + +pub(crate) struct Open { + pub id: DialogId, + pub preview: LivePreview, + /// The opening document's uid and revert count. + document: (u64, u64), +} + +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|doc| (doc.uid, doc.reverts) == self.document) + } + + /// Why OK is refused while the opening document is not the active one, after a revert too. + fn away(&self, app: &mut VectorcraftApp) -> Option { + if self.in_source(app) { + return None; + } + let (uid, _) = self.document; + if app.session.active().is_some_and(|doc| doc.uid == uid) { + let reason = tl!("The document was reverted. Reopen this dialog to continue."); + app.status(reason); + Some(reason.into()) + } else if app.session.documents().iter().any(|doc| doc.uid == uid) { + Some("switch back to the document where Step and Repeat was opened".into()) + } else { + Some("the document where Step and Repeat was opened has closed".into()) + } + } +} + +/// Rolls back the preview of an open dialog and drops its record. +fn cancel_open(app: &mut VectorcraftApp) { + if let Some(open) = app.object_dialogs.step.take() + && open.in_source(app) + { + open.preview.cancel(app); + } +} + +fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> { + let mut out = vec![]; + for id in selected { + if let Some(n) = doc.node(*id) { + n.walk(&mut |c| out.push((c.id.0, c.display_name()))); + } + } + out +} + +fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { + let mut out = vec![(String::new(), Label::from(tl!("Selection")))]; + if let Some(st) = app.session.active() { + out.extend(cut_ids(&st.doc, &st.selection.objects).into_iter().map(|(id, name)| (id.to_string(), Label::from(name)))); + } + out +} + +fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { + let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths); + vec![ + Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + len("gapX", tl!("Horizontal Gap")), + len("gapY", tl!("Vertical Gap")), + Param::new("cutId", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), + Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)), + len("margin", tl!("Margin")).enabled_when("fill", true), + Param::new( + "rotate", + tl!("Rotate 180°"), + ParamKind::choice( + vec![ + ("none".into(), Label::from(tl!("None"))), + ("columns".into(), Label::from(tl!("Every Other Column"))), + ("rows".into(), Label::from(tl!("Every Other Row"))), + ], + Some("none".into()), + ), + ), + ] +} + +pub fn fields() -> DialogFields { + DialogFields::from_pairs([ + ("rows", FieldValue::Int(2)), + ("columns", FieldValue::Int(2)), + ("gapX", FieldValue::Number(12.0)), + ("gapY", FieldValue::Number(12.0)), + ("margin", FieldValue::Number(0.0)), + ("fill", FieldValue::Bool(false)), + ("cutId", FieldValue::Text(String::new())), + ("rotate", FieldValue::Text("none".into())), + ]) +} + +fn count(f: &DialogFields, key: &str) -> u64 { + f.int(key).or_else(|| f.number(key).map(|n| n as i64)).unwrap_or(1).max(1) as u64 +} + +fn params(f: &DialogFields) -> Value { + let mut p = Map::new(); + p.insert("rows".into(), json!(count(f, "rows"))); + p.insert("columns".into(), json!(count(f, "columns"))); + for k in ["gapX", "gapY", "margin"] { + p.insert(k.into(), json!(f.number(k).unwrap_or(0.0))); + } + p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false))); + p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none"))); + if let Some(id) = f.text("cutId").and_then(|t| t.parse::().ok()) { + p.insert("cutId".into(), json!(id)); + } + Value::Object(p) +} + +pub(crate) fn open(app: &mut VectorcraftApp) { + let _ = try_open(app); +} + +fn try_open(app: &mut VectorcraftApp) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Rolls back the preview of a dialog this one replaces, before the cut paths are listed. + cancel_open(app); + let document = app.session.active().map(|doc| (doc.uid, doc.reverts)).ok_or("no document")?; + let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); + let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); + let cuts = cut_options(app); + let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { + ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)) + }); + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; + if let Some(reason) = open.away(app) { + app.object_dialogs.step = Some(open); + return Err(reason); + } + let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields)); + if done.is_err() { + app.object_dialogs.step = Some(open); + } + done.map(|_| ()) + }; + let cancel: Box = Box::new(cancel_open); + let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; + app.object_dialogs.step = Some(Open { id, preview: LivePreview::default(), document }); + Ok(Value::Null) +} + +/// Each frame: previews the dialog's values on the opening document while Preview is on. Another +/// document, or the opening one after a revert, gets no preview. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + if !app.object_dialogs.step.as_ref().is_some_and(|open| open.in_source(app)) { + return; + } + let Some(mut open) = app.object_dialogs.step.take() else { return }; + let shown = + app.dialogs().and_then(|host| host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields()))))); + if let Some((on, p)) = shown { + let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p); + } + app.object_dialogs.step = Some(open); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cut_path_is_sent_only_when_one_is_chosen() { + let mut f = fields(); + assert!(params(&f).get("cutId").is_none()); + f.set("cutId", FieldValue::Text("42".into())); + assert_eq!(params(&f)["cutId"], json!(42)); + } + + #[test] + fn cut_choices_reach_objects_nested_in_groups() { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [inner, c]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let ids: Vec = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect(); + assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i))); + } + + type Harness = egui_kittest::Harness<'static, VectorcraftApp>; + + /// An app with two documents, each with one selected square, the first one active. + fn two_documents() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for x in [20, 70] { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app + } + + /// A harness that shows the dialog host and runs this module's pump each frame. + fn start(app: VectorcraftApp) -> Harness { + let mut ready = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut ready, true) { + crate::testing::install(ui.ctx()); + app.adopt_context(ui.ctx()); + return; + } + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + pump(app, ui.ctx()); + crate::dialogs::host::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h + } + + fn id(h: &Harness) -> DialogId { + h.state().object_dialogs.step.as_ref().expect("Step and Repeat is open").id + } + + fn set(h: &mut Harness, key: &str, value: Value) { + let (ctx, id) = (h.ctx.clone(), id(h)); + h.state().dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, key, value)).unwrap(); + h.run_steps(2); + } + + fn confirm(h: &mut Harness) { + let (ctx, id) = (h.ctx.clone(), id(h)); + assert!(h.state().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)) || h.state().object_dialogs.step.is_some()); + h.run_steps(3); + } + + fn objects(h: &Harness) -> usize { + h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len() + } + + #[test] + fn preview_and_ok_stay_on_the_opening_document() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6, "the opening document previews 2 × 3"); + + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let other = h.state().session.doc().unwrap().doc.clone(); + set(&mut h, "columns", json!(4)); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Preview must leave the other document unchanged"); + confirm(&mut h); + assert_eq!(h.state().session.doc().unwrap().doc, other, "OK must leave the other document unchanged"); + assert!(h.state().object_dialogs.step.is_some(), "the dialog stays open"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK applies on the opening document"); + assert_eq!(objects(&h), 8); + } + + #[test] + fn reopening_rolls_back_the_earlier_preview() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "preview", json!(false)); + assert_eq!(objects(&h), 1, "the first dialog's preview is rolled back"); + assert!(!h.state().session.in_interaction()); + set(&mut h, "columns", json!(3)); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK of the reopened dialog applies"); + assert_eq!(objects(&h), 6); + } +} diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index a19a5160fc..e9fc5a9794 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,5 +1,5 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, -//! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or +//! object ids, decimals, encoding, units, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with //! them as `svg: {…}`. Show in Browser (`file.export.svg.browser`) writes the SVG the choices give //! to a temporary folder and opens it in the default browser, leaving the dialog open. @@ -56,6 +56,8 @@ const IMAGES: [(&str, &str); 2] = [("embed", "Embed"), ("link", "Link")]; const OBJECT_IDS: [(&str, &str); 3] = [("layerNames", "Layer Names"), ("minimal", "Minimal"), ("unique", "Unique")]; const PROFILES: [(&str, &str); 2] = [("svg11", "SVG 1.1"), ("tiny12", "SVG Tiny 1.2")]; const ENCODINGS: [(&str, &str); 3] = [("utf8", "Unicode (UTF-8)"), ("utf16", "Unicode (UTF-16)"), ("latin1", "ISO 8859-1")]; +const UNITS: [(&str, &str); 6] = + [("document", "Document"), ("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")]; /// Dialog fields that are not SVG options. const UI_KEYS: [&str; 5] = ["mode", "path", "showCode", "allArtboards", "range"]; @@ -72,11 +74,12 @@ pub(crate) struct SvgCodeKey { selected: Option>, } -/// The options a first SVG Options dialog starts from: the engine's defaults with Internal CSS -/// and Responsive on (as the reference app's Export As starts). Hidden layers are left to the -/// command (Save keeps them, Export leaves them out). +/// The options a first SVG export starts from: the engine's defaults with Pixels, +/// Internal CSS and Responsive on. Saves choose Document unless a remembered unit overrides it. +/// Hidden layers are left to the command (Save keeps them, Export leaves them out). pub(super) fn first_use() -> Map { - let mut m = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default(); + let opts = vectorcraft_svg::ExportOptions { units: Some(vectorcraft_svg::SizeUnit::Px), ..Default::default() }; + let mut m = serde_json::to_value(opts).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default(); m.remove("hiddenLayers"); m.insert("styling".into(), json!("css")); m.insert("responsive".into(), json!(true)); @@ -109,6 +112,10 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, mode: Mode, path: Option<&str> fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } + if mode != Mode::Export && saved.as_ref().unwrap_or(&app.ui.svg_options).get("units").is_none() { + // A document's legacy SVG options must not inherit Pixels from the last export. + fields.insert("units".into(), json!("document")); + } fields.insert("allArtboards".into(), json!(true)); fields.insert("range".into(), json!("")); if let Some(p) = path { @@ -146,7 +153,7 @@ fn pairs(key: &str, label: &'static str, choices: &[(&str, &'static str)]) -> Pa /// responsive, ``s and metadata. `screens` (Export for Screens' Format Settings) leaves out /// Images and Variable Data: a linked image is another file. `tiny`: SVG Tiny has presentation /// attributes alone and no web fonts. -pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec { +pub(crate) fn svg_params(mode: Mode, screens: bool, tiny: bool) -> Vec { let styling = pairs("styling", tl!("Styling:"), &STYLING); let fonts = ParamKind::radio(FONTS.iter().map(|(v, l)| ((*v).to_string(), tl!(*l).into())).collect(), Some("false".into())); let (lo, hi) = (*vectorcraft_svg::DECIMALS.start() as f64, *vectorcraft_svg::DECIMALS.end() as f64); @@ -161,6 +168,9 @@ pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec { rows.push(pairs("objectIds", tl!("Object IDs:"), &OBJECT_IDS)); rows.push(Param::number("decimals", tl!("Decimal:"), 3.0, 1.0, 0).bounds(Some(lo), Some(hi))); rows.push(pairs("encoding", tl!("Encoding:"), &ENCODINGS)); + // Responsive omits width and height, so the unit has nothing to act on. + let units = if mode == Mode::Export { &UNITS[1..] } else { &UNITS[..] }; + rows.push(pairs("units", tl!("Units:"), units).enabled_when("responsive", false)); rows.push(check("minify", tl!("Minify"), false)); rows.push(check("responsive", tl!("Responsive"), true)); // Embedded fonts need SVG 1.1 and text that stays text. @@ -189,7 +199,7 @@ fn artboard_rows(count: usize) -> Vec { /// Every row of the dialog for `mode`. Export Selection writes the selection's crop, without /// artboards to choose. fn dialog_params(mode: Mode, selection: bool, count: usize, tiny: bool) -> Vec { - let mut rows = svg_params(false, tiny); + let mut rows = svg_params(mode, false, tiny); match mode { Mode::Export if !selection => rows.extend(artboard_rows(count)), Mode::Export => {} @@ -211,6 +221,9 @@ fn options(mode: Mode, f: &DialogFields) -> Value { let tiny = f.text("profile") == Some("tiny12"); let mut o = json_of(&dialog_params(mode, false, 1, tiny), f); o.retain(|k, _| !UI_KEYS.contains(&k.as_str()) && !k.starts_with("__")); + if o.get("units").and_then(Value::as_str) == Some("document") { + o.remove("units"); + } if mode == Mode::Export { o.remove("preserveEditing"); if f.bool("useArtboards").unwrap_or(false) { @@ -663,6 +676,77 @@ mod tests { assert_eq!(fields(&app).number("decimals"), Some(1.0)); } + #[test] + fn svg_options_write_and_remember_units_and_decimals() { + let (mut app, written) = app(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + set(&mut app, "responsive", json!(false)); + set(&mut app, "units", json!("mm")); + set(&mut app, "decimals", json!(1)); + confirm(&mut app); + let svg = text(&written, 0); + assert!(svg.contains("mm\"") && svg.contains("viewBox=\"0 0 120 80\""), "{svg}"); + assert_eq!(app.ui.svg_options["decimals"], 1); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + assert_eq!(fields(&app).text("units"), Some("mm")); + set(&mut app, "responsive", json!(true)); + confirm(&mut app); + let svg = text(&written, 2); + assert!(!svg.contains("mm\"") && svg.contains("viewBox=\"0 0 120 80\""), "{svg}"); + } + + #[test] + fn legacy_svg_saves_keep_document_units() { + for mode in [Mode::Save, Mode::SaveCopy] { + for last in [json!({"responsive": false}), json!({"responsive": false, "units": "px"})] { + let (mut app, written) = app(); + let original = std::env::temp_dir().join("vc-original.svg").to_string_lossy().replace('\\', "/"); + let path = std::env::temp_dir().join("vc-saved.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": original, "svg": {"responsive": false}})).unwrap(); + let before = vectorcraft_svg::import(&text(&written, 0)).unwrap(); + app.ui.svg_options = last; + start(&mut app, mode, &path, false); + confirm(&mut app); + let after = vectorcraft_svg::import(&text(&written, 1)).unwrap(); + assert_eq!(after.units, vectorcraft_doc::Unit::Millimeters, "{mode:?}: {}", text(&written, 1)); + let (a, b) = (before.artboards[0].rect, after.artboards[0].rect); + assert!((a.width() - b.width()).abs() < 1e-6 && (a.height() - b.height()).abs() < 1e-6, "{mode:?}: {a:?} -> {b:?}"); + let expected = if mode == Mode::SaveCopy { &original } else { &path }; + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(expected.as_str())); + } + } + } + + #[test] + fn svg_saves_keep_explicit_units_and_allow_pixel_overrides() { + for mode in [Mode::Save, Mode::SaveCopy] { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-explicit.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": path, "svg": {"responsive": false, "units": "in"}})).unwrap(); + app.ui.svg_options = json!({"responsive": false, "units": "px"}); + start(&mut app, mode, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 1)).unwrap().units, vectorcraft_doc::Unit::Inches); + start(&mut app, mode, &path, false); + set(&mut app, "units", json!("px")); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 2)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + } + + #[test] + fn svg_export_keeps_pixels_when_legacy_options_omit_units() { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-export.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.ui.svg_options = json!({"responsive": false}); + start(&mut app, Mode::Export, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 0)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + /// OK with a range the document lacks keeps the dialog open with the reason, writes nothing and /// remembers nothing. #[test] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c45284ba5a..38c156048e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1003,3 +1003,231 @@ fn a_failed_tool_choice_restores_the_brush_key_color_initiator() { assert_eq!(app.session.tool_id(), "rectangle", "Cancel must preserve the successful replacement"); assert_eq!(unchanged(&app), before); } + +/// The `key` of each dialog `ui.inspect` lists, bottom first. +fn dialog_keys(app: &VectorcraftApp) -> Vec { + let ctx = app.ui_ctx.clone().expect("a window app"); + let ui = crate::control::inspect(app, &ctx); + ui["dialogs"].as_array().into_iter().flatten().filter_map(|d| d["key"].as_str().map(str::to_string)).collect() +} + +/// The `key` of each dialog `ui.inspect` lists, bottom first, `None` for a dialog without one. +fn dialog_entries(app: &VectorcraftApp) -> Vec> { + let ctx = app.ui_ctx.clone().expect("a window app"); + let ui = crate::control::inspect(app, &ctx); + ui["dialogs"].as_array().into_iter().flatten().map(|d| d["key"].as_str().map(str::to_string)).collect() +} + +/// A drawing every dialog `ui.menuDialog` lists can open on: two artboards and two selected rectangles, the first a +/// crease, and for `command` a selected envelope when Reset or Envelope Options needs one. +fn menu_dialog_app(command: &str) -> VectorcraftApp { + let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2})).unwrap(); + let crease = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run(crate::addons::packaging::SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap(); + // A variable and a data set, for the dialogs that edit one. + app.session.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + app.session.execute("dataset.new", &json!({"name": "Row"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + if let Some(make) = envelope_for(command) { + app.session.execute(make, &json!({})).unwrap(); + } + app +} + +/// The command that makes the envelope `command`'s dialog needs selected, if it needs one. +fn envelope_for(command: &str) -> Option<&'static str> { + match command { + "object.envelope.resetWithWarp" | "object.envelope.options" => Some("object.envelope.makeWithWarp"), + "object.envelope.resetWithMesh" => Some("object.envelope.makeWithMesh"), + _ => None, + } +} + +/// The part of `doc` after `start`, up to the first of `ends`; empty when `doc` does not have `start`. +fn clause<'a>(doc: &'a str, start: &str, ends: &[char]) -> &'a str { + let Some(at) = doc.find(start) else { return "" }; + let rest = &doc[at + start.len()..]; + &rest[..rest.find(ends).unwrap_or(rest.len())] +} + +/// Whether `clause` names command `id` as a word of its own. +fn names(clause: &str, id: &str) -> bool { + clause.split([' ', ',']).any(|word| word == id) +} + +/// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect` +/// reports: the command id unless the text names another key for that command, none for the commands the text says +/// have no key, and the slider's key for Smooth and Simplify, whose sliders show over the canvas. Every key the text +/// names is one a listed command opens. +#[test] +fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; + let list = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0; + let keyless = clause(doc, "the dialogs of ", &[';']); + let except = clause(doc, "is the command id, except ", &[';']); + let mut opened = Vec::new(); + for id in list.split('|') { + let expected = except + .split(',') + .filter_map(|entry| entry.split_once('`')?.1.split_once("` for ")) + .find_map(|(key, commands)| names(commands, id).then_some(key)) + .unwrap_or(id); + let mut app = menu_dialog_app(id); + app.run("ui.menuDialog", json!({"command": id})).unwrap_or_else(|e| panic!("{id}: {e}")); + settle(&mut app); + let entries = dialog_entries(&app); + assert_eq!( + entries.last().is_some_and(Option::is_none), + names(keyless, id), + "{id}: whether its dialog has a `key` differs from the params text" + ); + let keys: Vec = entries.into_iter().flatten().collect(); + match keys.last() { + None => assert!(names(keyless, id), "{id} opens no dialog"), + Some(key) => assert_eq!(key, expected, "{id}: its dialog key differs from the params text"), + } + // Smooth and Simplify open the slider over the canvas, which ui.inspect lists under its own key. + let showing = match id { + "object.path.simplify" => crate::dialogs::simplify_slider::showing(&app), + "object.path.smooth" => crate::dialogs::smooth_slider::showing(&app), + _ => true, + }; + assert!(showing, "{id}: its slider is not showing"); + opened.extend(keys); + } + for named in except.split('`').skip(1).step_by(2) { + assert!(opened.iter().any(|key| key == named), "the params text names `{named}`, which no listed command opens"); + } + // Simplify opens its dialog, under its command id, with the kept tolerance once OK in that dialog has kept the + // settings. + let mut app = menu_dialog_app("object.path.simplify"); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); + settle(&mut app); + set_all(&mut app, [("tolerance", json!(7.5)), ("retain", json!(true))]); + assert!(confirm(&mut app), "OK in the Simplify dialog is taken"); + settle(&mut app); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + assert_eq!(dialog_keys(&app), ["object.path.simplify"]); + assert_eq!(field(&app, "tolerance"), Some(7.5), "the reopened dialog shows the kept tolerance"); + assert!(flag(&app, "retain"), "the reopened dialog keeps Retain on"); +} + +/// Every command whose dialog `ui.menuDialog` opens and `ui.inspect` lists, with a `key` or without one, is one its +/// params text lists. Open Simplify and Smooth sliders count as dialogs too. +#[test] +fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; + let list: Vec<&str> = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0.split('|').collect(); + let mut app = menu_dialog_app(""); + let ids: Vec = + app.session.commands().into_iter().map(|c| c.id.to_string()).chain(crate::menus::UI_COMMANDS.iter().map(|c| c.0.to_string())).collect(); + let mut missing = Vec::new(); + for id in ids { + // The Reset and Envelope Options dialogs open only with an envelope selected. + if envelope_for(&id).is_some() { + app = menu_dialog_app(&id); + } + if app.run("ui.menuDialog", json!({"command": id})).is_err() { + if envelope_for(&id).is_some() { + app = menu_dialog_app(""); + } + continue; + } + settle(&mut app); + let opened = + !dialog_entries(&app).is_empty() || crate::dialogs::simplify_slider::showing(&app) || crate::dialogs::smooth_slider::showing(&app); + if opened && !list.contains(&id.as_str()) { + missing.push(id.clone()); + } + app = menu_dialog_app(""); + } + assert!(missing.is_empty(), "ui.menuDialog opens a dialog for {missing:?}, which its params text does not list"); +} + +/// The transform, selection and Type on a Path tools' `tool.options` open dialogs whose `key` its params text names. +#[test] +fn tool_options_opens_the_dialog_keys_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3; + let plain = doc.replace('`', ""); + assert!(plain.contains("key in ui.inspect"), "the params text must say the dialog names are the `key` in ui.inspect"); + let field = clause(&plain, "returned dialog field holds ", &['.']); + // The `dialog` value the params text gives for `tool`: " for " pairs, where names the tool + // itself (with a phrase rather than a `|` list of tool ids, and every value in the transform group) or one + // value for every tool in . + let documented_dialog = |tool: &str| -> Option { + let mut mappings = field.split(", ").map(|part| part.trim_start_matches("and ")).filter_map(|part| { + let (values, tools) = part.split_once(" for ")?; + if tools.contains(' ') && values.split('|').any(|v| v == tool) { + Some(tool.to_string()) + } else if tools.split('|').any(|t| t == tool) { + Some(values.to_string()) + } else { + None + } + }); + let mapping = mappings.next(); + assert!(mappings.next().is_none(), "{tool}: the params text gives more than one `dialog` mapping"); + mapping + }; + let groups = ["rotate|scale|reflect|shear", "selection|directSelection|groupSelection", "typeOnPath|verticalTypeOnPath"]; + let checked: Vec<&str> = groups.iter().flat_map(|g| g.split('|')).collect(); + let mut named_tools = Vec::new(); + for part in field.split(", ").map(|part| part.trim_start_matches("and ")) { + let (values, tools) = part.split_once(" for ").unwrap_or_else(|| panic!("`{part}` pairs no dialog value with tools")); + let named = if tools.contains(' ') { + assert!(values.split('|').all(|value| groups[0].split('|').any(|tool| tool == value)), "`{part}` names a non-transform tool"); + values + } else { + tools + }; + for tool in named.split('|') { + assert!(checked.contains(&tool), "the params text gives a `dialog` value for {tool}, which this test does not check"); + assert!(!named_tools.contains(&tool), "{tool}: the params text gives more than one `dialog` mapping"); + named_tools.push(tool); + } + } + for group in groups { + let documented = clause(doc, &format!("{group} → "), &[';']); + let keys: Vec<&str> = documented.split('`').skip(1).step_by(2).collect(); + let tools: Vec<&str> = group.split('|').collect(); + assert!(keys.len() == 1 || keys.len() == tools.len(), "{group}: the params text must pair tools with dialog keys"); + for (index, tool) in tools.into_iter().enumerate() { + let expected = keys[if keys.len() == 1 { 0 } else { index }]; + let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + if tool.ends_with("OnPath") { + let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap(); + app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); + } + let response = app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); + let expected_dialog = + documented_dialog(tool).unwrap_or_else(|| panic!("{tool}: the params text does not say which `dialog` its response holds")); + assert_eq!(response["dialog"], expected_dialog.as_str(), "{tool}: its response names a `dialog` other than the params text's"); + settle(&mut app); + let keys = dialog_keys(&app); + let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); + assert_eq!(key, expected, "{tool}: its dialog key differs from the params text"); + assert!(doc.contains(&format!("`{key}`")), "{tool} opens `{key}`, which the tool.options params text does not name"); + } + } +} + +/// More Options on the Simplify slider opens the dialog whose `key` the ui.simplifyMoreOptions params text names. +#[test] +fn simplify_more_options_opens_the_dialog_key_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.simplifyMoreOptions").expect("registered").3; + let mut app = menu_dialog_app("object.path.simplify"); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); + settle(&mut app); + let keys = dialog_keys(&app); + let key = keys.last().expect("More Options opens a dialog"); + assert!(doc.contains(&format!("(dialog `{key}`")), "More Options opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 3b96687a49..c9383d0f44 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -117,6 +117,20 @@ fn pdf_page_footer_ok_opens_the_chosen_range() { assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); } +#[test] +fn confirming_a_desktop_pdf_import_queues_the_read_and_closes_the_dialog() { + crate::opening::tests::with_threads(|| { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("three.pdf".into())).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); + confirm(&mut app).unwrap(); + assert!(!is_open(&app)); + assert_eq!(app.opening.pending.len(), 1); + assert_eq!(app.opening.pending[0].path, "three.pdf"); + }); +} + #[test] fn opening_a_multi_page_pdf_asks_for_the_pages() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e9a2166fa7..f54cd71999 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -326,3 +326,149 @@ fn path_sliders_close_when_file_revert_restores_the_artwork() { assert!(app.session.in_interaction()); } } + +/// The two sliders: the dialog key `ui.inspect` lists, the menu command that opens it and its undo step's name. +const PATH_SLIDERS: [(&str, &str, &str); 2] = + [("simplifySlider", "object.path.simplify", "Simplify"), ("smoothSlider", "object.path.smooth", "Smooth")]; + +/// One control channel request, answered at once. +fn control(app: &mut VectorcraftApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let ctx = app.ui_ctx.clone().unwrap(); + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method} answered later") }; + r +} + +/// The open dialog `key` in `ui.inspect`'s `dialogs`. +fn inspected_dialog(app: &mut VectorcraftApp, key: &str) -> Option { + let r = control(app, "ui.inspect", json!({})); + r["result"]["dialogs"].as_array()?.iter().find(|d| d["key"] == key).cloned() +} + +/// Both sliders show in `ui.inspect` as the dialog their params text names, with field `level`. `ui.dialog.set` +/// moves the slider and previews the level, and `ui.dialog.confirm` keeps the result as one undo step. +#[test] +fn path_sliders_show_in_ui_inspect_and_ui_dialog_confirm_keeps_the_level() { + for (key, command, label) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let open = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect")); + assert!(open["fields"]["level"].is_number(), "{open}"); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["fields"]["level"], 20.0, "{r}"); + let preview = app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).map(|p| p.1); + assert_eq!(preview, Some(json!({"level": 20.0})), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(json!(20.0)), "{key}"); + + let r = control(&mut app, "ui.dialog.confirm", json!({"dialog": key})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } +} + +/// A repeated level succeeds, but another active edit blocks a set and leaves the slider's level unchanged. +#[test] +fn path_sliders_refuse_a_set_when_another_edit_owns_the_interaction() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + for _ in 0..2 { + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 30})); + assert_eq!(r["ok"], true, "{key}: {r}"); + } + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + app.session.cancel_interaction().unwrap(); + app.begin_interaction("Other").unwrap(); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], false, "{key}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level), "{key}"); + } +} + +/// `ui.dialog.set` with `action` sets the level and answers in one request, replying `{dialog, result}` with the +/// slider as the set left it: `confirm` keeps the level as one undo step, and `cancel` puts the paths back. +#[test] +fn path_sliders_answer_a_set_with_an_action_in_one_request() { + for (key, command, label) in PATH_SLIDERS { + for action in ["confirm", "cancel"] { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "fields": [{"field": "level", "value": 30}], "action": action})); + assert_eq!(r["ok"], true, "{key} {action}: {r}"); + assert_eq!(r["result"]["dialog"]["key"], key, "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["level"], 30.0, "{r}"); + assert!(r["result"].get("result").is_some(), "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key} {action}"); + assert!(!app.session.in_interaction(), "{key} {action}"); + let history = &app.session.doc().unwrap().history; + if action == "confirm" { + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } else { + assert_eq!(history.undo.len(), undo_len, "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + } + } + } +} + +/// With a hosted dialog open over a slider, `ui.inspect` lists the slider first, and `"top"` names the hosted dialog. +#[test] +fn path_sliders_list_below_a_hosted_dialog_that_top_names() { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&mut app); + app.run("ui.javascriptFilesDialog", json!({})).unwrap(); + let r = control(&mut app, "ui.inspect", json!({})); + let open = r["result"]["dialogs"].as_array().cloned().unwrap_or_default(); + assert!(open.len() >= 2 && open[0]["key"] == "simplifySlider", "{open:?}"); + let r = control(&mut app, "ui.dialog.cancel", json!({"dialog": "top"})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, "simplifySlider").is_some(), "the hosted dialog closed, the slider stays"); + let r = control(&mut app, "ui.inspect", json!({})); + assert_eq!(r["result"]["dialogs"].as_array().map(Vec::len), Some(open.len() - 1), "{r}"); +} + +/// `ui.dialog.cancel` on the top dialog puts the paths back, as Escape does. A level outside 0..100, a value that +/// isn't a number and another field are refused, and the slider keeps its level. +#[test] +fn path_sliders_answer_ui_dialog_cancel_and_refuse_bad_fields() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + for bad in [json!({"field": "level", "value": 101}), json!({"field": "level", "value": "20"}), json!({"field": "tolerance", "value": 2})] { + let mut params = bad.clone(); + params["dialog"] = json!(key); + let r = control(&mut app, "ui.dialog.set", params); + assert_eq!(r["ok"], false, "{key} {bad}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key} {bad}"); + } + + let r = control(&mut app, "ui.dialog.cancel", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len, "{key}"); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 392e77a4ed..0378bbb2a6 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -345,13 +345,9 @@ fn a_dirty_documents_save_is_written_before_its_package() { app.session.execute("prefs.set", &json!({"values": {"backgroundExport": false}})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); package_dialog(&mut app, &out); - let opener = gate.clone(); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(50)); - opener.open(); - }); + let waited = gate.open_on_wait(); reply(&mut app).unwrap(); - release.join().unwrap(); + assert!(waited.get(), "the package waited for the save"); assert_eq!(written(&files), [doc]); assert!(app.background.jobs.is_empty() && !app.session.active().unwrap().is_dirty()); assert!(app.ui.status.starts_with("Packaged 3 files in "), "the package's status came last: {}", app.ui.status); @@ -451,14 +447,10 @@ fn a_package_made_at_once_waits_for_one_in_the_background() { // the background. app.session.execute("prefs.set", &json!({"values": {"backgroundExport": false}})).unwrap(); package_dialog(&mut app, &out); - let opener = gate.clone(); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(500)); - opener.open(); - }); + let waited = gate.open_on_wait(); reply(&mut app).unwrap(); + assert!(waited.get(), "the package made at once waited for the one in the background"); assert!(app.background.jobs.is_empty(), "the package in the background was written first"); - release.join().unwrap(); assert_eq!(written(&files).len(), 3); assert!(std::path::Path::new(&out).join("card Folder/card.vectorcraft").is_file()); } diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index c02363e9f5..795c540b64 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -257,3 +257,67 @@ fn an_open_plugin_dialog_follows_a_change_of_language() { assert_eq!(shown, (false, true), "the label in German"); assert_eq!(values.unwrap()["size"].as_f64(), Some(7.0), "the value set before"); } + +/// The width of every path in the active document together, in points. +fn paths_width(app: &VectorcraftApp) -> Option { + let doc = &app.session.doc().ok()?.doc; + let mut ids = Vec::new(); + doc.walk(|n| { + if n.path_data().is_some() { + ids.push(n.id); + } + }); + doc.bounds_of(&ids, false).map(|r| r.x1 - r.x0) +} + +/// Values typed and clicked in a plug-in's dialog reach the plug-in: a check box shows the row +/// whose `visibleWhen` it meets, the number typed there previews on the canvas, and OK runs the +/// filter with it as one undo step. +#[test] +fn typed_plugin_values_show_rows_and_reach_the_preview_and_the_run() { + use crate::tests::panel_harness::Panel; + let id = "test.ui.fields.typed"; + let manifest = format!( + r#"{{"id":"{id}","name":"Typed Values","version":"1","kind":"filter","params":{{ + "grow":{{"type":"bool","default":false,"label":"Grow"}}, + "n":{{"type":"int","min":0,"max":10,"default":3,"label":"Count","visibleWhen":{{"grow":[true]}}}}}}}}"# + ); + // A 30 pt wide triangle when the filter is given `n` 7, a 50 pt square otherwise. + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[30,0]},{"p":[15,20]}]}]}}]}"#; + let square = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[50,0]},{"p":[50,50]},{"p":[0,50]}]}]}}]}"#; + let wasm = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""n":7"#, triangle, square)).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("plugin.dialog", json!({"id": id})).unwrap(); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Count"), "Count is hidden while Grow is off"); + panel.click("Grow"); + panel.frame(); + assert_eq!(fields(&panel.app())["grow"], json!(true), "the click reaches the dialog's values"); + assert!(panel.shows("Count"), "checking Grow shows Count"); + panel.click("Count"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("7"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + let typed = fields(&panel.app())["n"].clone(); + let previewed = paths_width(&panel.app()); + let undo = panel.app().session.doc().unwrap().history.undo.len(); + panel.click("OK"); + panel.frame(); + panel.frame(); + let (closed, steps, ran) = { + let app = panel.app(); + (!app.any_dialog_open(), app.session.doc().unwrap().history.undo.len(), paths_width(&app)) + }; + panel.app().run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(typed.as_f64(), Some(7.0), "the typed count reaches the dialog's values"); + assert_eq!(previewed, Some(30.0), "the typed count previewed"); + assert!(closed, "OK closed the dialog"); + assert_eq!(steps, undo + 1, "one undo step"); + assert_eq!(ran, Some(30.0), "the filter ran with the typed count"); +} diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 89961fe1da..01266d6a18 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -653,14 +653,10 @@ fn an_export_made_at_once_waits_for_one_in_the_background() { let p = json!({"folder": folder, "formats": [{"format": "svg"}]}); assert_eq!(app.run("file.exportForScreens", p.clone()).unwrap()["background"], true); background_export(&mut app, false); - let opener = gate.clone(); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(500)); - opener.open(); - }); + let waited = gate.open_on_wait(); let r = app.run("file.exportForScreens", p).unwrap(); + assert!(waited.get(), "the export made at once waited for the one in the background"); assert!(app.background.jobs.is_empty(), "the export in the background was written first"); - release.join().unwrap(); let file = format!("{folder}/Artboard-1.svg"); assert_eq!((written(&files), r["files"].clone()), (vec![file.clone()], json!([file]))); assert_eq!(app.ui.status, format!("Exported 1 file to {folder}")); diff --git a/crates/ui-egui/src/dialogs/transform.rs b/crates/ui-egui/src/dialogs/transform.rs index 7437183918..d0618d050a 100644 --- a/crates/ui-egui/src/dialogs/transform.rs +++ b/crates/ui-egui/src/dialogs/transform.rs @@ -150,11 +150,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) { let document = app.session.active().map(|doc| (doc.uid, doc.reverts)); let rows = rows(app, kind, &opening); let fields = fields_of(&rows, &opening); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| { if kind == Kind::Move { link_distance_and_angle(f); } let dialog = ParamDialog::new(kind.command(), kind.title(), rows.clone()).previews(true).values(Bind::bound(f)); + let dialog = match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + }; if kind == Kind::Move { dialog.remember(MOVE_KEY) } else { dialog } }); // A dialog this one replaces leaves its preview behind otherwise. diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index b0b1a7c7d9..eb4e0b6522 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -18,7 +18,8 @@ use craft::ui::contract::{Props as _, ShowContainer as _}; use craft::ui::runtime::windows::WindowHost; -use craft::ui::shell::DocumentWindow; +use craft::ui::shell::{DocumentWindow, Frame, TitleBar}; +use craft::ui::style::SurfaceKind; use serde_json::{Value, json}; use crate::VectorcraftApp; @@ -446,6 +447,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let is_current = views::current(app) == Some(win); let live = is_current && !crate::menus::home_showing(app); let mut pressed = false; + let mut tab_close = false; let mut found = (None, None, false); let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin)); let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window }; @@ -456,7 +458,16 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } // A press anywhere on the window, its title bar and tab included, makes its document current. pressed = pressed_on_layer(ui); - crate::chrome::window_tab(app, ui, win); + // Where the app draws the OS window's frame, the tab sits in a title bar: its free area moves the + // window and its captions act on it. The fallback layer has a title row of its own. + let app_frame = !matches!(WindowHost::of(ui.ctx()).frame(), Frame::Native); + if ui.ctx().viewport_id() != egui::ViewportId::ROOT && app_frame { + let tab = |ui: &mut egui::Ui, _: &mut craft::ui::contract::BodyCx<'_>| tab_close |= crate::chrome::window_tab(app, ui, win); + let bar = TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, tab, |_, _| {}); + tab_close |= bar.close_requested; + } else { + tab_close = crate::chrome::window_tab(app, ui, win); + } let areas = [(win, ui.available_rect_before_wrap())]; let unfitted = crate::canvas::panes::refit_resized(app, &areas); // The display that shows the window, the size of its body and whether its view fits it in this frame. @@ -479,7 +490,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { x.place = placed.translate(-origin); } } - if out.close_requested.is_some() { + if out.close_requested.is_some() || tab_close { close = Some(win); } else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() { activate = Some(win); diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 4e7905cb9f..2e86cf9552 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -602,12 +602,15 @@ fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks /// each to close while `close` is set. Each /// window is 500 × 400 points with its top-left corner at `origin` on the screen, and its next -/// frame takes `events`. +/// frame takes `events`. `commands` gathers the commands the windows' frames sent, and `strip` is where the last +/// window drew its tab strip, in its own points. #[derive(Default)] struct Host { close: bool, origin: Pos2, events: Vec, + commands: Vec, + strip: Option, } fn native_host() -> std::rc::Rc> { @@ -638,6 +641,14 @@ fn native_host() -> std::rc::Rc> { let input = egui::RawInput { viewport_id: id, viewports, screen_rect: Some(rect), events, ..Default::default() }; let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); full.textures_delta.clear(); + let mut shared = shared.borrow_mut(); + shared.commands.extend(full.viewport_output.values().flat_map(|out| out.commands.iter().cloned())); + let nodes = full.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]); + let strip = + nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TabList && n.label() == Some("Window")).and_then(|(_, n)| n.bounds()); + if let Some(b) = strip { + shared.strip = Some(egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + } }); host } @@ -666,6 +677,79 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { assert_eq!(app.ui.floating.len(), 1, "its window is still shown"); } +/// [`crate::testing::ui_context`] with the frame the desktop host gives a window on Windows: no OS title bar, so the +/// app draws the title bar and its caption buttons. +fn integrated_frame_context() -> egui::Context { + use craft::window::policy::{Backend, Desktop, Os, Runtime, TitleBarPref, WindowKind, decide}; + let desktop = Desktop::detect(Backend::X11); + let decision = decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + assert!(matches!(decision.frame, Frame::Integrated(_)), "{:?}", decision.frame); + let ctx = egui::Context::default(); + craft::ui::shell::embed::install(&ctx, craft::ui::testing::install_spec().frame(decision), &crate::ui_fonts()).expect("the runtime installs"); + craft::ui::testing::windows::set_os(&ctx, Os::Windows); + let prefs = vectorcraft_engine::Prefs::default(); + let print = crate::state::print_ppi(prefs.display_print_size, None); + craft::ui::runtime::frame::set_input(&ctx, craft::ui::runtime::frame::FrameInput::new(crate::app::root_env(&prefs, 1.0, print))); + ctx +} + +/// A floating document's OS window without an OS title bar moves when the free part of the bar holding its tab is +/// dragged. +#[test] +fn a_floating_os_window_without_an_os_title_bar_moves_by_the_bar_of_its_tab() { + let host = native_host(); + let ctx = integrated_frame_context(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !WindowHost::of(&ctx).viewports_available() { + // Wayland: the windows are inside the main window, where the layer's title row moves them. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + host.borrow_mut().commands.clear(); + // Just right of the tab strip, on the bar's free band, in the window's own points. + let strip = host.borrow().strip.expect("the window drew its tab strip"); + let at = pos2(strip.right() + 8.0, strip.center().y); + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(at)], + vec![button(at, true)], + vec![egui::Event::PointerMoved(at + vec2(10.0, 4.0))], + vec![egui::Event::PointerMoved(at + vec2(30.0, 12.0))], + vec![button(at + vec2(30.0, 12.0), false)], + ] { + host.borrow_mut().events = events; + let out = run_frame(&mut app, &ctx, vec![]); + commands.extend(out.viewport_output.values().flat_map(|v| v.commands.iter().cloned())); + } + commands.append(&mut host.borrow_mut().commands); + assert!(commands.contains(&egui::ViewportCommand::StartDrag), "the drag moves the window: {commands:?}"); + assert!(is_floating(&app, 1), "the document still floats"); +} + +/// A floating document's tab keeps its close button: a middle click on it, as on a tab under the main strip, closes +/// the window and its document. +#[test] +fn a_floating_documents_tab_closes_its_window() { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[0].title(); + let tab = window_tab_at(&shapes, &title, window_of(&app, &ctx, 0)); + let middle = |pressed| egui::Event::PointerButton { pos: tab, button: egui::PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab), middle(true)]); + frame(&mut app, &ctx, vec![middle(false)]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.documents().len(), 1, "its document closed"); + assert!(app.ui.floating.is_empty(), "its window closed"); +} + /// The update prompt, opening on its own, takes the keyboard once from a document's OS window that /// has it, and leaves the keyboard alone when none of those windows has it. #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index fdaaebcee1..d5f31df6c3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,6 +1,8 @@ //! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or //! flyout panel. +use craft::ui::contract::{Props as _, Scroll, ShowContainer as _}; +use craft::ui::layout_components::Stack; use egui::Ui; use crate::state::DockTab; @@ -13,6 +15,29 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { Some(DockTab::Properties) => panels::properties::show(app, ui), Some(DockTab::Layers) => panels::layers::show(app, ui), Some(DockTab::Libraries) => panels::libraries(app, ui), + None if matches!( + id, + "align" + | "attributes" + | "blend" + | "character" + | "color" + | "docInfo" + | "magicWand" + | "openType" + | "paragraph" + | "pathfinder" + | "patternOptions" + | "stroke" + | "tabs" + | "transform" + | "transparency" + ) => + { + // These panels lay out forms. Collection panels own their scrolling viewport + // and reserve their own footer outside it. + Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id)); + } None => panels::show_icon_panel(app, ui, id), } } diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index 81bf88811c..1f1245000d 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -67,7 +67,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age)); return; } - if app.any_dialog_open() { + // Progress is modal for input, but the window must not block itself on its next pass. + if app.asking_dialog_open() { return; } let Shown { title, step, fraction, counts, queued, cancel, hide, .. } = shown; @@ -208,17 +209,21 @@ mod tests { assert_eq!(r["background"], true, "{r}"); } let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert!(!frame(&mut app, &ctx).contains("Saving a.vectorcraft"), "not before the delay"); age(&mut app); frame(&mut app, &ctx); - let shown = frame(&mut app, &ctx); - assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}"); - assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}"); + let visible: Vec<_> = (0..6).map(|_| (frame(&mut app, &ctx), app.any_dialog_open())).collect(); assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2); assert!(!frame(&mut app, &ctx).contains("Saving"), "hidden saves aren't shown"); assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled"); go.store(true, std::sync::atomic::Ordering::SeqCst); background::wait_all(&mut app); + for (shown, modal) in visible { + assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}"); + assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}"); + assert!(modal, "progress remains modal for input"); + } assert!(app.background.jobs.is_empty()); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft")); app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap(); diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 65e2a030d2..6b49903050 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -1208,11 +1208,12 @@ mod tests { d.pending = Some(Action::ChangeAll); }); pump_now(&mut app); - assert!(fonts(&mut app).iter().all(|f| f["family"] == "Source Serif 4"), "the document changed"); - let d = opened(&app); let now = fonts(&mut app); + let families: Vec<&Value> = now.iter().map(|f| &f["family"]).collect(); + assert_eq!(families, [&json!("Source Serif 4")], "the document changed"); + let d = opened(&app); assert_eq!(d.rows, replacement_rows(&app, "document", &now), "the rows follow the document"); - assert!(d.rows.iter().all(|r| r.family == "Source Serif 4"), "{:?}", d.rows); + assert_eq!(d.rows.iter().map(|r| r.family.as_str()).collect::>(), ["Source Serif 4"], "{:?}", d.rows); assert!(d.pending.is_none(), "the press was taken"); } diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index 0ff54d12d3..27cf2c623c 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -10,6 +10,10 @@ //! - The web host then starts again with new graphics and a new egui context, handing it the same //! app. The app notices the new context and makes everything it uploaded to the old one again: //! its fonts and theme, the canvas, and every texture cache ([`TexCache`]). +//! - The desktop host can't give the window a new device. When the window closes after a loss +//! ([`GraphicsLoss::happened`]), the process ends once the app has saved what it keeps on +//! quitting, before the window's graphics are torn down: releasing a swapchain that still holds +//! a frame the lost device couldn't present panics in the graphics driver layer (#6374). use std::cell::{Cell, Ref, RefCell, RefMut}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -20,7 +24,16 @@ use crate::VectorcraftApp; /// Raised by the host when the window's graphics device is lost (from any thread), read on the UI /// thread. Cheap to clone; the clones share the report. #[derive(Clone, Default)] -pub struct GraphicsLoss(Arc>>); +pub struct GraphicsLoss(Arc>); + +/// What a [`GraphicsLoss`] holds. +#[derive(Default)] +struct Loss { + /// The loss not handled yet, for [`GraphicsLoss::take`]. + why: Option, + /// A loss was reported at some point, handled or not. + happened: bool, +} impl GraphicsLoss { /// The graphics device was lost (`why`, for the log): the next frame of `ctx` handles it. A @@ -28,13 +41,23 @@ impl GraphicsLoss { pub fn report(&self, ctx: &egui::Context, why: impl Into) { let why = why.into(); log::error!("vectorcraft: the graphics device was lost: {why}"); - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(why); + { + let mut loss = self.0.lock().unwrap_or_else(|e| e.into_inner()); + loss.why.get_or_insert(why); + loss.happened = true; + } ctx.request_repaint(); } /// The loss reported since the last call, if any. pub fn take(&self) -> Option { - self.0.lock().unwrap_or_else(|e| e.into_inner()).take() + self.0.lock().unwrap_or_else(|e| e.into_inner()).why.take() + } + + /// Whether the device was lost at any point, a loss [`Self::take`] already handled included. + /// A window can't be given a new device, so once true this stays true. + pub fn happened(&self) -> bool { + self.0.lock().unwrap_or_else(|e| e.into_inner()).happened } } @@ -190,6 +213,16 @@ mod tests { assert_eq!(loss.take(), None, "handled once"); } + #[test] + fn a_handled_loss_is_still_known_when_the_window_closes() { + let (loss, ctx) = (GraphicsLoss::default(), crate::testing::ui_context()); + assert!(!loss.happened(), "nothing lost yet"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "the next frame handles it"); + assert!(loss.happened(), "the device stays lost after the frame handled the report"); + } + #[test] fn a_tex_cache_empties_when_the_ui_moves_to_a_new_context() { thread_local! { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 3a04ae86fb..5ea3433c56 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -69,13 +69,15 @@ static EMBEDDED: &Embedded = &[ ("fi", "", include_str!("i18n/fi.tsv")), ("tr", "", include_str!("i18n/tr.tsv")), ("ca", "", include_str!("i18n/ca.tsv")), + ("ar", "", include_str!("i18n/ar.tsv")), ]; /// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font /// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a -/// bundled Gujarati face) is not offered, including when restoring a preference. +/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept +/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> { - EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "gu" || !web || gujarati_font).collect() + EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect() } /// The one catalog set of the process, built on first use. @@ -141,7 +143,7 @@ impl LangExt for Lang { } fn complete_menus(self) -> bool { - self != Lang::EN + self != Lang::EN && self.code() != "ar" } fn from_code(code: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv new file mode 100644 index 0000000000..0920934df4 --- /dev/null +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -0,0 +1,8 @@ +# Arabic (ar) catalog. Same format as zh-hant.tsv: context source translation +# (empty context = a plain UI string; `@id` = a command id; `@plural` = 6 CLDR forms; +# `@msg` = a status or error message). +# +# Translations are maintained upstream in storytold/craft-i18n (locales/ar/vectorcraft.tsv) +# under AGENTS.md rule 16. +@id language.name العربية +@plural {n} commit|{n} commits {n} إيداع|{n} إيداع|{n} إيداعين|{n} إيداعات|{n} إيداعًا|{n} إيداع diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index bfb29c30da..3dca49857f 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -7,9 +7,9 @@ fn lang(code: &str) -> Lang { Lang::from_code(code).unwrap_or_else(|| panic!("{code} registered")) } -/// The languages that are not English, the source language. +/// The languages that are not English, the source language, and have complete catalogs. fn translated() -> Vec { - Lang::all().filter(|l| *l != Lang::EN).collect() + Lang::all().filter(|l| l.complete_menus()).collect() } /// (language, context, English source, the term the language's glossary gives it). One row per @@ -173,6 +173,28 @@ fn numbered_labels_translate_the_name_before_the_number() { assert_eq!(numbered_label(Lang::EN, "Grays 12"), "Grays 12"); } +#[test] +fn arabic_is_preparatory_and_unavailable_to_users() { + assert_eq!(Lang::from_code("ar"), None); + assert!(!Lang::for_picker().iter().any(|l| l.code() == "ar")); + assert_eq!(Lang::from_pref("ar"), Lang::from_pref("auto")); +} + +#[test] +fn arabic_plural_rule_and_catalog_infrastructure() { + let (i18n, problems) = I18n::new(EMBEDDED, &["ar"]); + assert!(problems.is_empty(), "{problems:?}"); + let ar = i18n.from_code("ar").expect("ar offered in custom instance"); + assert_eq!(i18n.name(ar), "العربية"); + for tag in ["ar", "AR", "ar-SA", "ar_EG", "ar_EG.UTF-8", "ar-AE", "ar-MA"] { + assert_eq!(i18n.match_tag(tag), Some(ar), "{tag}"); + } + for (n, want) in [(0, "0 إيداع"), (1, "1 إيداع"), (2, "2 إيداعين"), (3, "3 إيداعات"), (11, "11 إيداعًا"), (100, "100 إيداع")] + { + assert_eq!(i18n.trn_plain(ar, n, "{n} commit", "{n} commits"), want, "for n={n}"); + } +} + #[test] fn current_language_is_a_frame_setting() { set_current(ZH()); @@ -798,11 +820,12 @@ fn literal_spans(code: &str) -> Vec<(usize, usize)> { out } -/// For translators, `cargo test -p vectorcraft-ui-egui dump_source_strings` writes every English -/// interface string to `VECTORCRAFT_I18N_DUMP=`, and every status and error message as a +/// For translators, `cargo test -p vectorcraft-ui-egui dump_source_strings -- --ignored` writes every +/// English interface string to `VECTORCRAFT_I18N_DUMP=`, and every status and error message as a /// catalog template that [`untranslated_report`] checks to `VECTORCRAFT_I18N_DUMP_MESSAGES=`, /// one per line. #[test] +#[ignore = "translator tool: writes the files VECTORCRAFT_I18N_DUMP and VECTORCRAFT_I18N_DUMP_MESSAGES name"] fn dump_source_strings() { if let Ok(path) = std::env::var("VECTORCRAFT_I18N_DUMP") { let mut all = crate::menus::menu_strings(); @@ -813,27 +836,11 @@ fn dump_source_strings() { std::fs::write(path, text).expect("write dump"); } if let Ok(path) = std::env::var("VECTORCRAFT_I18N_DUMP_MESSAGES") { - std::fs::write(path, message_dump()).expect("write dump"); + let text: String = reported_messages().iter().map(|m| format!("{m}\n")).collect(); + std::fs::write(path, text).expect("write dump"); } } -/// The text [`dump_source_strings`] writes to `VECTORCRAFT_I18N_DUMP_MESSAGES`. -fn message_dump() -> String { - reported_messages().iter().map(|m| format!("{m}\n")).collect() -} - -/// The translators' message dump lists every message the untranslated report checks, the -/// phrases a parameter schema's error builds included. -#[test] -fn message_dump_lists_the_reported_messages() { - let dump = message_dump(); - let lines: std::collections::BTreeSet<&str> = dump.lines().collect(); - for phrase in SCHEMA_PHRASES { - assert!(lines.contains(phrase), "the dump skips {phrase:?}"); - } - assert!(lines.contains("the color book is cut short")); -} - /// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English. const KEEPS_MENU_NAMES: [&str; 20] = ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca"]; @@ -1199,9 +1206,9 @@ fn reported_messages() -> std::collections::BTreeSet { } /// The untranslated report checks the messages of the effects and of the crates whose errors the -/// engine and the effects pass on, and the phrases a parameter schema's error builds. +/// engine and the effects pass on. #[test] -fn untranslated_report_checks_every_message_crate_and_schema_phrase() { +fn untranslated_report_checks_every_message_crate() { let reported = reported_messages(); let passed_on = [ ("effects", "the SVG filter has no primitives"), @@ -1214,9 +1221,6 @@ fn untranslated_report_checks_every_message_crate_and_schema_phrase() { assert!(message_literals_in(&[krate]).contains(m), "{krate}: {m}"); assert!(reported.contains(m), "the report skips {krate}: {m}"); } - for phrase in SCHEMA_PHRASES { - assert!(reported.contains(*phrase), "the report skips the schema phrase {phrase:?}"); - } } /// Banner Hems and Grommets' errors and the status of a recovery copy that failed without a folder @@ -1914,6 +1918,54 @@ fn f(p: &Value) -> Result<()> { assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]); } +/// What the parameter schema's error says a value of `ty` must be, for `bad`, a value of another +/// type. +fn schema_expected(ty: vectorcraft_apischema::Type, bad: serde_json::Value) -> String { + use vectorcraft_apischema::{Param, ParamSchema, Problem}; + let params: &'static [Param] = Box::leak(Box::new([Param::new("v", ty)])); + let refused = ParamSchema::new(params, "").validate(&serde_json::json!({ "v": bad })); + match refused { + Err(e) => match e.problem { + Problem::WrongType { expected, .. } => expected, + other => panic!("{ty:?} refused {other:?}, not a value of the wrong type"), + }, + Ok(_) => panic!("{ty:?} took a value of another type"), + } +} + +/// `text` with each of `values`, found in order, written as the next unnamed placeholder. +fn with_placeholders(text: &str, values: &[&str]) -> String { + let (mut out, mut rest) = (String::new(), text); + for (n, value) in values.iter().enumerate() { + let at = rest.find(value).unwrap_or_else(|| panic!("{text:?} does not hold {value:?}")); + out.push_str(&rest[..at]); + out.push_str(&format!("{{_{}}}", n + 1)); + rest = &rest[at + value.len()..]; + } + out + rest +} + +/// The phrase the parameter schema's error builds for a number's range and unit, an integer's +/// range, a choice of names and a value with no range is one [`SCHEMA_PHRASES`] lists, with the +/// schema's own values as placeholders. +#[test] +fn schema_phrases_hold_what_the_schema_error_says() { + use vectorcraft_apischema::{Bound, Type}; + let cases: [(Type, serde_json::Value, &[&str]); 7] = [ + (Type::NUMBER, "x".into(), &[]), + (Type::Number { min: Some(Bound::Inclusive(1.5)), max: Some(Bound::Inclusive(2.5)), unit: None }, "x".into(), &["1.5", "2.5"]), + (Type::Number { min: Some(Bound::Exclusive(1.5)), max: Some(Bound::Inclusive(2.5)), unit: Some("pt") }, "x".into(), &["1.5", "2.5", "pt"]), + (Type::Number { min: None, max: Some(Bound::Exclusive(2.5)), unit: Some("deg") }, "x".into(), &["2.5", "deg"]), + (Type::Integer { min: Some(3), max: None }, "x".into(), &["3"]), + (Type::Enum(&["left", "right"]), true.into(), &["\"left\", \"right\""]), + (Type::Array(&Type::String), "x".into(), &[]), + ]; + for (ty, bad, values) in cases { + let phrase = with_placeholders(&schema_expected(ty, bad), values); + assert!(SCHEMA_PHRASES.contains(&phrase.as_str()), "{ty:?}: SCHEMA_PHRASES lacks {phrase:?}"); + } +} + /// The phrases a parameter schema's error uses for what a value must be, as `@msg` sources: one /// for each type, and for a number each range and unit form. const SCHEMA_PHRASES: &[&str] = &[ diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 96719fa0c9..eb2a544af8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -4,31 +4,8 @@ /// The Selection and Direct Selection arrows' fill, painted black or white under their outline. pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg"); +/// VectorCraft's own `dc-*` icons, drawn with 1.5-unit strokes in a 24-unit view box. pub static ICONS: &[(&str, &[u8])] = &[ - ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), - ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), - ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), - ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), - ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), - ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), - ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), - ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), - ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), - ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), - ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), - ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), - ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), - ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), - ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), - ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), - ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), - ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), - ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), - ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), - // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. - ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), - ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), - ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("dc-actions", include_bytes!("../../../assets/icons/dc-actions.svg")), ("dc-al-bottom", include_bytes!("../../../assets/icons/dc-al-bottom.svg")), ("dc-al-center", include_bytes!("../../../assets/icons/dc-al-center.svg")), @@ -244,6 +221,34 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-wrinkle", include_bytes!("../../../assets/icons/dc-wrinkle.svg")), ("dc-zoom-large", include_bytes!("../../../assets/icons/dc-zoom-large.svg")), ("dc-zoom-small", include_bytes!("../../../assets/icons/dc-zoom-small.svg")), +]; + +/// Lucide icons the built-in catalog lacks, drawn with Lucide's 2-unit strokes in a 24-unit view box. +pub static LUCIDE_ICONS: &[(&str, &[u8])] = &[ + ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), + ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), + ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), + ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), + ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), + ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), + ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), + ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), + ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), + ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), + ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), + ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), + ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), + ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), + ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), + ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), + ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), + ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), + ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), + ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), + // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. + ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), + ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), + ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")), ("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 30b6edfb49..a544de7e90 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -2,14 +2,24 @@ use craft::ui::primitives::{AppIcons, icon_names}; -use crate::icon_data::{DC_ARROW_FILL, ICONS}; +use crate::icon_data::{DC_ARROW_FILL, ICONS, LUCIDE_ICONS}; /// The fills of the Selection and Direct Selection arrows: black and white whatever the theme, as users /// know them, under an outline in the theme's colour. const FILLS: &[(&str, &[u8], [u8; 4])] = &[("dc-selection", DC_ARROW_FILL, [0, 0, 0, 255]), ("dc-direct", DC_ARROW_FILL, [255, 255, 255, 255])]; -/// The app's icons, for `register_app_icons`. -pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.6), ICONS).with_fills(FILLS); +/// The app's own icons, for `register_app_icons`. The stroke width is the documents' own, so the framework redraws +/// their strokes at the width it draws the catalog's. +pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.5), ICONS).with_fills(FILLS); + +/// The Lucide icons the catalog lacks, with Lucide's own stroke width. +pub static LUCIDE_APP_ICONS: AppIcons = AppIcons::new("vectorcraft-lucide", Some(2.0), LUCIDE_ICONS); + +/// Registers both of the app's icon sets beside the framework's catalog. +pub fn register() { + craft::ui::primitives::register_app_icons(&APP_ICONS); + craft::ui::primitives::register_app_icons(&LUCIDE_APP_ICONS); +} /// Map tool-catalogue icon names to the names of icons that resolve. pub fn tool_icon(name: &str) -> &'static str { @@ -114,23 +124,63 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-print-tiling" => "dc-print-tiling", "tool-zoom" => "zoom_in", // A name that is already an icon maps to itself, as the `'static` name of the set that has it. - other => icon_names().iter().copied().chain(APP_ICONS.icons.iter().map(|(n, _)| *n)).find(|n| *n == other).unwrap_or("rect_dashed"), + other => icon_names() + .iter() + .copied() + .chain(APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons).map(|(n, _)| *n)) + .find(|n| *n == other) + .unwrap_or("rect_dashed"), } } #[cfg(test)] mod tests { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; // PLAN: assumed the `craft` facade is a dependency of vectorcraft-ui-egui (Cargo.toml is not in this set's files; craft-ui does not re-export IconId) use craft::behavior::IconId; use super::*; fn resolves(name: &'static str) -> bool { - register_app_icons(&APP_ICONS); + register(); has_icon(&IconId::new(name)) } + /// The SVG document of the app icon `name`, from either set. + fn app_svg(name: &str) -> String { + let (_, bytes) = ICONS.iter().chain(LUCIDE_ICONS).find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an app icon")); + String::from_utf8_lossy(bytes).into_owned() + } + + /// The `stroke-width` the document's root `` element sets, the width of every stroke that sets none of its + /// own; `None` for a document drawn with fills. + fn root_stroke_width(svg: &str) -> Option { + let root = svg.split("').next()?; + Some(root.split("stroke-width=\"").nth(1)?.split('"').next()?.parse().unwrap_or(f32::NAN)) + } + + // Regression test: the tool rail's icons drew uneven outlines. The app set declared a 1.6-unit stroke while its own icons drew 1.5 and + // its Lucide copies drew 2, so the framework drew them 6% thinner and 25% heavier than the catalog's icons. + /// The framework scales every stroke in a set by the drawn width over the set's declared width, so an icon's + /// outline matches the catalog's only when its root stroke width equals its set's declared width. Details with + /// a width of their own keep their ratio to the outline. + #[test] + fn every_app_icon_draws_its_outline_at_the_catalog_width() { + let mut off = Vec::new(); + for set in [&APP_ICONS, &LUCIDE_APP_ICONS] { + let declared = set.stroke_width.unwrap_or_else(|| panic!("{} declares its stroke width", set.name)); + for (name, bytes) in set.icons { + let Some(width) = root_stroke_width(&String::from_utf8_lossy(bytes)) else { continue }; + // The outline's drawn width relative to the catalog's. + let relative = width / declared; + if !(0.99..=1.01).contains(&relative) { + off.push(format!("{name} in {}: {width} draws at {relative:.3} of the catalog width", set.name)); + } + } + } + assert!(off.is_empty(), "app icons whose outlines do not draw at the catalog width: {off:#?}"); + } + /// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`. const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""]; @@ -153,7 +203,7 @@ mod tests { /// app's set. Other ids built in match arms and tuple tables are not scanned. #[test] fn every_icon_id_literal_and_panel_icon_resolves() { - register_app_icons(&APP_ICONS); + register(); let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned()))); let (mut seen, mut unknown) = (0, Vec::new()); let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; @@ -212,10 +262,7 @@ mod tests { // as opaque as the line, so the line vanished where it crossed the bar. #[test] fn the_cap_icons_mark_the_path_end_in_one_place_over_a_lighter_stroke() { - let svg = |name: &str| { - let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an icon")); - String::from_utf8_lossy(bytes).into_owned() - }; + let svg = app_svg; // The end-of-path line is the icon's last shape, a vertical line `M{x} …V…`. let end_line = |icon: &str| -> String { let last = icon.rsplit(">(); let pen = shapes(&svg("tool-pen")); @@ -331,7 +373,7 @@ mod tests { assert!(resolves(name), "{} maps to {name}, which no icon set has", tool.icon); } let catalog = icon_names(); - for (name, _) in APP_ICONS.icons { + for (name, _) in APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons) { assert!(!catalog.contains(name), "{name} is in the catalog: the app's copy is refused"); } } diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 673f78af10..e5c59365b1 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -233,13 +233,19 @@ fn open_request<'a>(purpose: &str, folder: Option, filters: impl IntoIte /// Asks for a file to open with `request`; `then` gets its path. The web answers with the file's /// bytes, which open as File › Open opens them (the extension decides). A cancelled picker runs -/// nothing. While it is open the reply is `{pending: "fileDialog"}`. +/// nothing, and a picker that failed (the browser could not read the file) reports why. While it is +/// open the reply is `{pending: "fileDialog"}`. While another file dialog is still open, which can +/// be a window the system placed out of sight, the reply is an error saying so (#6160): a second +/// picker would only wait behind the first. fn ask_open( app: &mut VectorcraftApp, request: PickRequest, owner: Owner, then: impl FnOnce(&mut VectorcraftApp, String) -> Result + 'static, ) -> Result { + if app.file_dialog_open() { + return Err(file_asks::busy().into()); + } Ok(file_asks::ask(app, request, owner, move |app, picked| match picked { Picked::Contents(files) => { for (name, bytes) in &files { @@ -247,6 +253,7 @@ fn ask_open( } Ok(Value::Null) } + Picked::Failed(error) => Err(error), picked => match picked.first_path() { Some(path) => then(app, path.to_string_lossy().into_owned()), None => Err("cancelled".into()), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3cd948fce0..8a931c60b3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -372,13 +372,22 @@ pub struct VectorcraftApp { impl VectorcraftApp { /// Whether a layer that takes the keys (a modal dialog, a popup) showed in the last pass, or a - /// modal dialog opened since: a command or a canvas gesture waits while one does. A modeless - /// dialog blocks nothing, and the job progress window does not count (its layer has the - /// progress role). False before the app has a context. + /// modal dialog opened since: a command or a canvas gesture waits while one does. This includes + /// job progress, which is a modal layer. pub(crate) fn any_dialog_open(&self) -> bool { + self.dialog_open(OpenFilter::Modal) + } + + /// Whether a question or popup is open. Applying a job's result can close its progress window. + pub(crate) fn asking_dialog_open(&self) -> bool { + self.dialog_open(OpenFilter::Asks) + } + + /// Whether a layer matching the filter, a popup or a pending app modal is open. + fn dialog_open(&self, filter: OpenFilter) -> bool { // A modeless layer with a focus scope (the canvas's task bar) takes keys too, and blocks nothing. let popup = |ctx: &egui::Context| overlay::top(ctx).and_then(|id| overlay::entry(ctx, id)).is_some_and(|e| e.rank == overlay::Rank::Popup); - self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, OpenFilter::Modal) || popup(ctx)) + self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, filter) || popup(ctx)) || self.dialogs().is_some_and(|d| d.with(|h| h.shows_modal())) } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d017a1a181..568b9a36d3 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -92,6 +92,8 @@ pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; +#[cfg(test)] +pub(crate) use state::WHY_OFF_ASKED; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use state::{command_shortcuts, shown_state_with, why_off}; pub(crate) use submenus::PATH_EFFECTS; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 06d9a22523..d94e4feef4 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -118,6 +118,9 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if any(|k| matches!(k, NodeKind::Compound { .. })) { v.push(c("Release Compound Path", "object.compoundPath.release")); } + if vectorcraft_engine::can_create_outlines(&app.session) { + v.push(c("Create Outlines", "type.createOutlines")); + } // The paragraphs of the selected type, or those the Type tool's selection touches. if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 69722bd1ae..66353c55be 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -1,7 +1,9 @@ +use craft::keymap::{Chord, CommandRef}; + use super::context::context_items; -use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; +use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut_in, spelling_item_label, unlock_item_label}; use super::slots::{recent_readable, recent_slot}; -use super::state::{shortcut_of, shown_state}; +use super::state::{command_shortcuts, shown_state}; use super::tree::{Listed, menu_tree_named}; use super::{Node, Serialize, Value, VectorcraftApp, unbound}; @@ -32,8 +34,9 @@ pub struct MenuEntry { /// Flattened menu for `ui.menu.list`. pub fn menu_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; + let chord = command_shortcuts(app); for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english, &Listed::of(app)) { - flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); + flatten(app, &chord, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); } out } @@ -41,7 +44,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec { /// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus). pub fn context_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; - flatten(app, vec![], vec![], &context_items(app), &mut out); + flatten(app, &command_shortcuts(app), vec![], vec![], &context_items(app), &mut out); out } @@ -166,7 +169,15 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec, shown: Vec, nodes: &[Node], out: &mut Vec) { +/// `nodes` flattened into `out`, each item's shortcut looked up in `chord` ([`command_shortcuts`]). +pub(super) fn flatten( + app: &VectorcraftApp, + chord: &dyn Fn(&CommandRef) -> Option, + path: Vec, + shown: Vec, + nodes: &[Node], + out: &mut Vec, +) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry { @@ -197,7 +208,10 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec, shown: Vec {} } diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index fffff70049..73a4296dd9 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -40,9 +40,15 @@ pub(crate) struct Menus { /// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the /// first: the `input` of [`state_key`]. pressed: Option, + /// The address of the window's keymap that the panel rows took their shortcuts from ([`keymap_addr`]), `None` + /// before the window has one. + keymap: Option, /// How many times [`refresh`] built the model. #[cfg(test)] pub(crate) rebuilds: u64, + /// How many times [`refresh`] set the keymap's shortcuts again without building the model ([`refresh_shortcuts`]). + #[cfg(test)] + pub(crate) shortcut_refreshes: u64, /// The menus as built, before a layout. pub(crate) bar: MenuBar, /// `bar` laid out for the shell's target: what the in-window bar shows. @@ -89,20 +95,31 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash /// doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's -/// preview, or a typing session), the revision, which each of its previews changes, is left out: -/// the hash changes as the interaction begins and as it ends. +/// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one, +/// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An +/// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check +/// for an open interaction change state then and the menus stay open while it previews. The window's keymap, which the +/// shown shortcuts are read from, is in the hash too. pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { + let mut h = DefaultHasher::new(); + (rows_key(app, input), keymap_addr(app)).hash(&mut h); + h.finish() +} + +/// [`state_key`] without the window's keymap: what the model's rows are built from. A new keymap alone changes only +/// the shortcuts of the rows that read it, which [`refresh`] sets again without a rebuild ([`refresh_shortcuts`]). +fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); - // The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it - // after the first frame's menus, and builds a new one when the bindings or the catalog change. - app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h); + // The user's shortcuts, which the catalog's rows are made from. + std::sync::Arc::as_ptr(&app.shortcut_overrides).addr().hash(&mut h); let s = &app.session; (s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h); if let Some(d) = s.active() { - let revision = d.interaction.is_none().then_some(d.revision); - (d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h); + let revision = d.interaction.as_ref().map_or(d.revision, |it| it.revision); + let previewing = d.interaction.as_ref().is_some_and(|it| !it.by_tool()); + (d.uid, revision, previewing, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h); } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); // Apply Last Filter and Last Filter… are named after the filter that ran last. @@ -126,12 +143,19 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { } /// Brings the menus up to date once per frame, before the frame's input: the model is built again -/// when the rows' state ([`state_key`]) or the shell's target changed. +/// when the rows' state ([`rows_key`]) or the shell's target changed. When only the window's keymap +/// changed (the framework builds the first one after the first frame's menus), the rows that read +/// their shortcuts from it get them again ([`refresh_shortcuts`]). pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { let target = Target::of_shell(&WindowHost::of(ctx).shell()); let press = last_press(app, ctx); - let key = state_key(app, press); + let key = rows_key(app, press); + let keymap = keymap_addr(app); if app.menus.key == Some(key) && app.menus.target == Some(target) { + if app.menus.keymap != keymap { + refresh_shortcuts(app, target); + app.menus.keymap = keymap; + } return; } rebuild(app, target); @@ -141,6 +165,54 @@ pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.menus.key = Some(key); app.menus.target = Some(target); + app.menus.keymap = keymap; +} + +/// The address of the window's keymap, which the panel rows read their shortcuts from ([`reads_keymap`]): the framework +/// builds it after the first frame's menus, and builds a new one when the bindings or the catalog change. +fn keymap_addr(app: &VectorcraftApp) -> Option { + app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()) +} + +/// Whether the row running `id` with `params` shows a shortcut read from the window's keymap ([`Build::decorate`]). +fn reads_keymap(id: &str, params: &Value) -> bool { + matches!(id, "window.panel" | "edit.preferences") && !params.is_null() +} + +/// Sets the shortcuts of the rows that read the window's keymap ([`reads_keymap`]) again and lays the bar out again. +/// The rows' states and the catalog stay as the last rebuild made them. +fn refresh_shortcuts(app: &mut VectorcraftApp, target: Target) { + fn walk(app: &VectorcraftApp, nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => { + let shortcut = super::labels::item_shortcut(app, &item.command.id, &item.command.params); + item.shortcut = shortcut; + } + Node::Submenu { children, .. } => walk(app, children), + _ => {} + } + } + } + let mut bar = std::mem::take(&mut app.menus.bar); + for menu in &mut bar.menus { + walk(app, &mut menu.children); + } + app.menus.bar = bar; + lay_out(app, target); + #[cfg(test)] + { + app.menus.shortcut_refreshes += 1; + } +} + +/// Lays `app.menus.bar` out for `target` into `app.menus.laid`, which is edited only when the laid-out bar differs. +fn lay_out(app: &mut VectorcraftApp, target: Target) { + let options = LayoutOptions::new(APP_NAME).label(&translate_label); + let laid = layout(&app.menus.bar, target, &options).bar; + if *app.menus.laid != laid { + app.menus.laid.edit(|l| *l = laid); + } } /// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read @@ -257,7 +329,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { // The Glyphs panel menu's East Asian glyph forms read the faces that draw the selected text from the layout this keeps. crate::panels::glyphs::refresh_form_faces(app); let listed = Listed::of(app); - let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new() }; + let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new(), checks: Checks::default() }; let menus: Vec = menu_tree_named(app.session.prefs.font_names_in_english, &listed) .into_iter() .map(|(title, nodes)| { @@ -267,7 +339,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { if translated { menu.english(title) } else { menu } }) .collect(); - let Build { mut states, refs, .. } = build; + let Build { mut states, refs, mut checks, .. } = build; // The catalog is built again only when what its rows are made from changed; edits and selection changes change // the rows' states alone. @@ -291,17 +363,12 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { CatalogRows { inputs, defs, known, accepted } } }; - row_states(app, &rows, &mut states); + row_states(app, &rows, &mut states, &mut checks); crate::panels::panel_menu_states(app, &mut states); - let bar = MenuBar::new(menus); - let options = LayoutOptions::new(APP_NAME).label(&translate_label); - let laid = layout(&bar, target, &options).bar; app.menus.rows = Some(rows); - app.menus.bar = bar; - if *app.menus.laid != laid { - app.menus.laid.edit(|l| *l = laid); - } + app.menus.bar = MenuBar::new(menus); + lay_out(app, target); app.menus.states.edit(|s| *s = states); } @@ -395,10 +462,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft: /// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row /// names. -fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) { +fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates, checks: &mut Checks) { for d in &rows.defs { if states.get(&d.command).is_none() { - states.set(d.command.clone(), row_state(app, &d.command, &d.label)); + states.set(d.command.clone(), row_state(app, &d.command, &d.label, checks)); } } // The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say @@ -406,11 +473,28 @@ fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStat for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) { let command = CommandRef::new(c.id); if states.get(&command).is_none() { - states.set(command.clone(), row_state(app, &command, c.label)); + states.set(command.clone(), row_state(app, &command, c.label, checks)); } } } +/// What [`why_off`] answered for each command id during one rebuild. The answer depends on the id and the app's state, +/// not on the row's params, so the rows that share an id (Effect's dialogs, Window's panels, the interface languages) +/// run their command's check once. +#[derive(Default)] +struct Checks(std::collections::HashMap>>); + +impl Checks { + fn why_off(&mut self, app: &VectorcraftApp, id: &str) -> Option> { + if let Some(why) = self.0.get(id) { + return why.clone(); + } + let why = why_off(app, id); + self.0.insert(id.to_owned(), why.clone()); + why + } +} + /// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles): /// the set's definition is the command's. With them, the keys each has beyond the set's, as the set's keys and those /// (Cut, Copy and Paste's F2, F3 and F4 outside macOS). @@ -445,10 +529,9 @@ fn linked_defaults(command: &CommandRef) -> Option> { /// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title /// where the app shows another. -fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState { +fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str, checks: &mut Checks) -> CommandState { let state_id = crate::keymap::state_id(command); - let why = why_off(app, state_id); - let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None)); + let (enabled, checked) = shown_state_with(app, state_id, &command.params, &mut |id| checks.why_off(app, id)).unwrap_or((false, None)); let mut state = CommandState::new().enabled(enabled); if let Some(on) = checked { state = state.checked(on); @@ -458,7 +541,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command state = state.title(shown.clone()); } if !enabled { - state = state.hint(off_reason_with(app, command, &shown, why)); + state = state.hint(off_reason_with(app, command, &shown, checks.why_off(app, state_id))); } state } @@ -493,6 +576,7 @@ struct Build<'a> { states: CommandStates, /// Every command reference the tree holds, its English label, and whether it is checkable. refs: Vec<(CommandRef, String, bool)>, + checks: Checks, } impl Build<'_> { @@ -548,22 +632,25 @@ impl Build<'_> { return Some(item); } let (id, params) = (command.id.as_str(), &command.params); - let why = why_off(self.app, id); - let (enabled, checked) = shown_state_with(self.app, id, params, &why)?; + let (app, checks) = (self.app, &mut self.checks); + let (enabled, checked) = shown_state_with(app, id, params, &mut |id| checks.why_off(app, id))?; let title = self.item_title(id, params, &item.label); let mut state = CommandState::new().enabled(enabled).title(title.clone()); if let Some(on) = checked { state = state.checked(on); } let mut item = item; - let tip = if id == "ui.expandDialog" && vectorcraft_engine::cmd::expand::has_appearance(&self.app.session) { - Some(crate::i18n::tr(self.lang, crate::dialogs::expand::appearance_first()).to_string()) + // Expand… dimmed for appearance attributes says so in its tooltip; `why` holds what its check found, kept from + // the state above. + let appearance_first = crate::dialogs::expand::appearance_first(); + let why = if id == "ui.expandDialog" { self.checks.why_off(self.app, id) } else { None }; + let tip = if why.as_ref().is_some_and(|w| w.as_deref() == Some(appearance_first)) { + Some(crate::i18n::tr(self.lang, appearance_first).to_string()) } else if enabled { None } else { // The reason reads the check of the command's state id, which is `id` but for the framework's own rows. - let state_id = crate::keymap::state_id(&command); - let why = if state_id == id { why } else { why_off(self.app, state_id) }; + let why = self.checks.why_off(self.app, crate::keymap::state_id(&command)); Some(off_reason_with(self.app, &command, &title, why)) }; if let Some(tip) = tip { @@ -597,7 +684,7 @@ impl Build<'_> { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. - "window.panel" | "edit.preferences" if !params.is_null() => { + _ if reads_keymap(id, params) => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item @@ -658,6 +745,93 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); } + /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's + /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus + /// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held + /// steady against tests running alongside, and the steps run again on a new app, at most 20 times, until the + /// other catalogs held still through them. + #[test] + fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { + fn clear(nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => item.shortcut = None, + Node::Submenu { children, .. } => clear(children), + _ => {} + } + } + } + fn panel_chords(bar: &MenuBar) -> usize { + bar.items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) + .count() + } + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let catalogs = || { + ( + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + crate::scripts_menu::revision(), + crate::dialogs::proof_setup::saved_revision(), + ) + }; + let run = || { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + let first = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + let chords = (panel_chords(&app.menus.bar), panel_chords(&app.menus.laid)); + refresh(&mut app, &ctx); + let second = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + (shown, first, chords, second) + }; + let (shown, first, chords, second) = (0..20) + .find_map(|_| { + let before = catalogs(); + let out = run(); + (catalogs() == before).then_some(out) + }) + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + assert!(shown > 0, "the panel rows show their shortcuts' chords"); + assert_eq!(first.0, 0, "a new keymap alone does not build the menus again"); + assert_eq!(first.1, 1, "the new keymap sets the shortcuts"); + assert_eq!(chords.0, shown, "the panel rows show their chords again"); + assert_eq!(chords.1, shown, "the laid-out bar shows them too"); + assert_eq!(second, (0, 1), "the same keymap sets nothing again"); + } + + /// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the + /// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown. + #[test] + fn a_rebuild_checks_a_shared_command_once() { + let (mut app, ctx) = app_with_document(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("select.all", json!({})).unwrap(); + super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear); + refresh(&mut app, &ctx); + let asked = super::super::state::WHY_OFF_ASKED.take(); + for id in ["effect.dialog", "window.panel", "app.language", "object.envelope.release"] { + assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}"); + } + assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled), "the states follow the selection"); + } + /// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together. #[test] fn a_rebuild_checks_each_dimmed_row_once() { @@ -677,4 +851,30 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed"); } } + + /// A rebuild walks the selection's appearance once for Object › Expand…, for its state and its tooltip together. + #[test] + fn a_rebuild_walks_the_appearance_once_for_expand() { + let (mut app, ctx) = app_with_document(); + let expand = CommandRef::new("ui.expandDialog"); + let tooltip = |app: &VectorcraftApp| app.menus.bar.items().into_iter().find(|it| it.command == expand).and_then(|it| it.tooltip.clone()); + let walks = |app: &mut VectorcraftApp| { + super::super::state::APPEARANCE_WALKS.set(0); + refresh(app, &ctx); + super::super::state::APPEARANCE_WALKS.get() + }; + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + assert_eq!(walks(&mut app), 1, "a plain rectangle"); + assert!(app.menus.states.get(&expand).is_some_and(CommandState::is_enabled)); + assert_eq!(tooltip(&app), None); + app.run("appearance.addFill", json!({})).unwrap(); + assert_eq!(walks(&mut app), 1, "two fills"); + assert!(app.menus.states.get(&expand).is_some_and(|s| !s.is_enabled())); + assert_eq!(tooltip(&app).as_deref(), Some(crate::dialogs::expand::appearance_first())); + app.run("select.none", json!({})).unwrap(); + assert_eq!(walks(&mut app), 0, "nothing selected"); + // Dimmed with nothing selected, the row keeps the general reason as its tooltip, as before. + let tip = tooltip(&app); + assert!(tip.as_deref().is_some_and(|t| t != crate::dialogs::expand::appearance_first()), "{tip:?}"); + } } diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 0cd3eeaa87..2450a9b201 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -27,7 +27,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) { let gate = Gate::default().modal(app.file_dialog_open()).recording_shortcut(recording_shortcut(app)).text_editing(ctx.egui_wants_keyboard_input()); let Some(menu) = app.services.native_menu.as_mut() else { return }; - menu.poll(ctx); menu.set_gate(gate); let clicks = menu.take_clicks(ctx); // A menu opening reads the Scripts folder again. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 11975b7c24..50e2a7606e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -734,6 +734,39 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err(e.to_string()), } } + "tool.quickPen.arcLarger" | "tool.quickPen.arcSmaller" => { + // `]` or `[`, for Ctrl+wheel over the canvas: the arc size 15° larger or smaller. Input + // held for an edit is finished first, as for Flip Arc. False, with nothing changed beyond + // that, while the Quick Pen tool is not active or the step would leave 1° to 359°. + match app.session.finish_tool_edit() { + Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)), + Err(e) => return Some(Err(e.to_string())), + } + if app.session.tool_id() != vectorcraft_tools::quickpen::ID { + return Some(Ok(json!(false))); + } + let key = + if id == "tool.quickPen.arcLarger" { vectorcraft_tools::ToolKey::BracketRight } else { vectorcraft_tools::ToolKey::BracketLeft }; + // A step changes the tool's size, or draws the arc again: as an edit between presses, or + // as the preview of a drag (applied, or kept for the release with Real-time Drawing off). + let state = |app: &VectorcraftApp| { + let d = app.session.active(); + ( + app.session.tool_options()["turn"].clone(), + d.map(|d| d.revision), + d.and_then(|d| d.interaction.as_ref()).and_then(|it| it.preview.clone()), + ) + }; + let before = state(app); + let view = app.view_info(); + match app.session.tool_key(key, vectorcraft_tools::Mods::default(), view) { + Ok(reqs) => { + crate::canvas::apply_requests(app, Ok(reqs)); + Ok(json!(state(app) != before)) + } + Err(e) => Err(e.to_string()), + } + } "window.dock" => match app.ui_ctx.clone() { // Tab: hide the panels, the toolbars and the Control bar, or show what the last Tab // hid; the window's shell applies it in its next pass. diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 80fb7475ad..6ae7c66be0 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -153,13 +153,14 @@ pub(super) fn hidden_when_disabled(id: &str) -> bool { /// Menu items another item stands in for right now: Envelope Distort's Reset with Warp and Reset /// with Mesh take the place of Make with Warp and Make with Mesh while an envelope is selected. -fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { +/// `why_off` answers [`why_off`] for Release's id. +fn swapped_out(id: &str, why_off: &mut dyn FnMut(&str) -> Option>) -> bool { let reset = match id { "object.envelope.makeWithWarp" | "object.envelope.makeWithMesh" => false, "object.envelope.resetWithWarp" | "object.envelope.resetWithMesh" => true, _ => return false, }; - enabled(app, "object.envelope.release") != reset + why_off("object.envelope.release").is_none() != reset } /// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite @@ -173,16 +174,21 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool { /// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden /// ([`east_asian_hidden`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - shown_state_with(app, id, p, &why_off(app, id)) + shown_state_with(app, id, p, &mut |id| why_off(app, id)) } -/// [`shown_state`] from `why`, what [`why_off`] answered for `id`: a caller that also writes the reason a dimmed row -/// gives runs the command's check once. -pub(crate) fn shown_state_with(app: &VectorcraftApp, id: &str, p: &Value, why: &Option>) -> Option<(bool, Option)> { - let en = why.is_none() +/// [`shown_state`] with `why_off` answering [`why_off`] for each command id it asks about: a caller that keeps the +/// answers runs each command's check once. +pub(crate) fn shown_state_with( + app: &VectorcraftApp, + id: &str, + p: &Value, + why_off: &mut dyn FnMut(&str) -> Option>, +) -> Option<(bool, Option)> { + let en = why_off(id).is_none() && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)) && (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p)); - if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) { + if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) { return None; } Some((en, checked(app, id, p))) @@ -295,9 +301,30 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> Err(why) => Some(Some(why)), }; } + if id == "ui.expandDialog" { + return expand_dialog_off(app); + } (!ui_enabled(app, id)).then_some(None) } +#[cfg(test)] +thread_local! { + /// How many times [`expand_dialog_off`] walked the selection's appearance on this thread. + pub(crate) static APPEARANCE_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Why Object › Expand… can't open now: dimmed with nothing selected, and with +/// [`crate::dialogs::expand::appearance_first`] for appearance attributes, which Expand Appearance expands first +/// (#3089). The selection's appearance is walked once, for the row's state and its tooltip together. +fn expand_dialog_off(app: &VectorcraftApp) -> Option> { + if !app.session.active().is_some_and(|d| !d.selection.is_empty()) { + return Some(None); + } + #[cfg(test)] + APPEARANCE_WALKS.set(APPEARANCE_WALKS.get() + 1); + vectorcraft_engine::cmd::expand::has_appearance(&app.session).then(|| Some(crate::dialogs::expand::appearance_first().to_string())) +} + /// Can UI command `id` run now? fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { match id { @@ -388,10 +415,6 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { id if id.starts_with(crate::panels::symbols::USER_SLOT) => crate::panels::symbols::user_library(app, id).is_some(), "ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app), id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(), - // Dimmed for appearance attributes, which Expand Appearance expands first (#3089). - "ui.expandDialog" => { - app.session.active().is_some_and(|d| !d.selection.is_empty()) && !vectorcraft_engine::cmd::expand::has_appearance(&app.session) - } "ui.spotColors" => app.session.active().is_some(), "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index b21b2e8ccf..88c2e04540 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -164,15 +164,29 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() { assert_eq!(menu.toggled("Pixel Snapping Options…"), None); } -/// A key press builds the menus' states again once: the frames after it, with no press, keep them. -#[test] -fn a_key_press_rebuilds_the_menus_once() { +/// An app with a new document whose installed fonts are cataloged, after the frames that build its first menus and the +/// window's keymap. It runs in a process of its own ([`crate::testing::in_own_process`]): the menus' key holds the +/// installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in that another test +/// installs, or a font it adds, rebuilds this app's menus. `None` in the parent process. +fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { + if !crate::testing::in_own_process(test) { + return None; + } let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. + vectorcraft_text::FontDb::global().family_list(); app.run("file.new", json!({})).unwrap(); let ctx = crate::testing::ui_context(); for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } + Some((app, ctx)) +} + +/// A key press builds the menus' states again once: the frames after it, with no press, keep them. +#[test] +fn a_key_press_rebuilds_the_menus_once() { + let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_rebuilds_the_menus_once") else { return }; let before = app.menus.rebuilds; for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); @@ -187,6 +201,28 @@ fn a_key_press_rebuilds_the_menus_once() { assert_eq!(app.menus.rebuilds, before + 1); } +/// A font added to the fonts the whole process shares builds the menus again with no input, Type › Font then lists it, +/// and the idle frames after that keep the menus. +#[test] +fn a_new_font_rebuilds_the_menus() { + const FAMILY: &str = "Menurebuild Sans"; + let Some((mut app, ctx)) = settled_app("menus::tests::a_new_font_rebuilds_the_menus") else { return }; + let lists = + |app: &VectorcraftApp| app.menus.bar.items().into_iter().any(|it| it.command.id == "text.setStyle" && it.command.params["font"] == FAMILY); + assert!(!lists(&app)); + let font = vectorcraft_text::test_fonts::named_copy(false, (FAMILY, "Regular", "Version 1.000", "MenurebuildSans-Regular")); + let before = app.menus.rebuilds; + assert_eq!(vectorcraft_text::FontDb::global().add_font(font.expect("the test font builds")), 1); + app_frame(&mut app, &ctx, vec![]); + assert!(app.menus.rebuilds > before, "the new font rebuilds the menus"); + assert!(lists(&app), "Type › Font lists {FAMILY}"); + let after = app.menus.rebuilds; + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } + assert_eq!(app.menus.rebuilds, after, "idle frames keep the menus"); +} + #[test] fn help_f1_opens_discover_without_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -401,7 +437,7 @@ fn menu_entry_shown_paths_keep_script_folder_names() { let items = vec![sub("Scripts", vec![sub("File", folder), cp("Other Script…", "ui.runScript", Value::Null)])]; let mut out = vec![]; crate::i18n::set_current(de); - flatten(&app, vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); + flatten(&app, &super::command_shortcuts(&app), vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); crate::i18n::set_current(crate::i18n::Lang::EN); let script = out.iter().find(|e| e.command.as_deref() == Some(crate::scripts_menu::COMMAND)).unwrap(); assert_eq!(script.path, ["File", "Scripts", "File"]); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index ff2f1b20d6..7cd830ef05 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -858,6 +858,7 @@ pub(super) fn transform_items() -> Vec { c("Shear…", "object.shear"), Sep, c("Transform Each…", "object.transformEach"), + c("Step and Repeat…", "object.stepAndRepeat"), Sep, c("Reset Bounding Box", "object.resetBoundingBox"), cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..b4cf91497d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -736,6 +736,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", ), + ( + "tool.quickPen.arcLarger", + "Increase Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° larger, for the last sharp-corner arc of the path being drawn and the arcs after it, as ] and Ctrl+wheel up over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size above 359°", + ), + ( + "tool.quickPen.arcSmaller", + "Decrease Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° smaller, for the last sharp-corner arc of the path being drawn and the arcs after it, as [ and Ctrl+wheel down over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size below 1°", + ), ( "window.dock", "Panels", @@ -1193,7 +1205,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1275,7 +1287,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. 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", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.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", @@ -1293,7 +1305,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1311,13 +1323,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1532,7 +1544,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1550,19 +1562,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", "More Options", "", - "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + "{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", ), ( "ui.dialogReset", @@ -1646,7 +1658,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1664,7 +1676,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1919,7 +1931,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::RESET, "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( crate::panels::actions::CLEAR, @@ -1950,7 +1962,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", @@ -2203,7 +2215,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5e72952fe2..541b033cff 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -148,7 +148,7 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver bool { - if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { + if app.asking_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { return false; } let s = &app.session; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index cdb55375db..d9f334105c 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -439,7 +439,9 @@ fn a_file_opened_under_automation_roots_finishes_under_them() { start(&mut app, "/art/Scoped.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(10.0, 10.0), false)) }); let scope = app.opening.pending[0].scope.clone(); - assert!(scope.run(file_access::current).is_some(), "the roots go with the open"); + assert!(file_access::current().is_none(), "the desktop has no roots here"); + let (given, kept) = (roots.expect("roots for the folder"), scope.run(file_access::current).expect("the roots go with the open")); + assert!(std::sync::Arc::ptr_eq(&given, &kept), "the open keeps the roots it started under"); } /// A file asked for again while it is still being read is not read a second time (#3455). @@ -545,16 +547,20 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { // The app's clock stands still: a read is only old enough for its window after `age`. app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert_eq!(progress(&mut app, &ctx), "", "nothing opening"); start(&mut app, "/art/Big.vectorcraft", bytes("Big")); assert_eq!(progress(&mut app, &ctx), "", "not at once"); age(&mut app); progress(&mut app, &ctx); // a new window measures itself unseen first - let texts = progress(&mut app, &ctx); - for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] { - assert!(texts.contains(want), "{want} in {texts}"); + for _ in 0..6 { + let texts = progress(&mut app, &ctx); + for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] { + assert!(texts.contains(want), "{want} in {texts}"); + } + assert!(!texts.contains("waiting"), "{texts}"); + assert!(app.any_dialog_open(), "progress remains modal for input"); } - assert!(!texts.contains("waiting"), "{texts}"); start(&mut app, "/art/Next.vectorcraft", bytes("Next")); let texts = progress(&mut app, &ctx); assert!(texts.contains("Opening Big.vectorcraft…") && texts.contains("waiting"), "{texts}"); @@ -569,6 +575,24 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { assert_eq!(app.session.documents().len(), before + 2); } +#[test] +fn a_file_ready_while_progress_is_visible_opens_without_hiding_progress() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.now_override = Some(0.0); + let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); + start(&mut app, "/art/Big.vectorcraft", bytes("Big")); + age(&mut app); + progress(&mut app, &ctx); + assert!(progress(&mut app, &ctx).contains("Opening Big.vectorcraft")); + assert!(app.any_dialog_open()); + + open_ready(&mut app); + assert!(app.opening.pending.is_empty()); + assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Big.vectorcraft")); + assert_eq!(progress(&mut app, &ctx), "", "completion closes progress"); +} + /// #5930: the progress window's Cancel (`file.cancelOpen`): the file doesn't open, even once it /// has been read, and the status bar no longer says it is opening. #[test] @@ -578,10 +602,11 @@ fn cancelling_an_open_opens_nothing() { let before = app.session.documents().len(); start(&mut app, "/art/Big.vectorcraft", bytes("Big")); assert!(crate::menus::enabled(&app, "file.cancelOpen")); + // The file has been read and its result waits for the next frame when Cancel is pressed. + wait_read(&mut app); assert_eq!(app.run("file.cancelOpen", json!({})).unwrap()["cancelled"], 1); assert!(app.opening.pending.is_empty() && !long_operation_busy(&app)); assert!(!app.ui.status.starts_with("Opening"), "{}", app.ui.status); - std::thread::sleep(std::time::Duration::from_millis(50)); poll(&mut app); assert_eq!(app.session.documents().len(), before); assert_ne!(app.ui.recent_files.first().map(String::as_str), Some("/art/Big.vectorcraft")); diff --git a/crates/ui-egui/src/paint_preview.rs b/crates/ui-egui/src/paint_preview.rs index ad49d9e373..2aaa86ba1b 100644 --- a/crates/ui-egui/src/paint_preview.rs +++ b/crates/ui-egui/src/paint_preview.rs @@ -300,11 +300,16 @@ mod tests { fn freeform_chip_shows_the_points_opacity() { use vectorcraft_color::{Freeform, FreeformPoint}; use vectorcraft_geom::kurbo::Point; - let mut gp = paint(GradientKind::Freeform, 0.0); - let clear = FreeformPoint { opacity: 0.0, ..FreeformPoint::new(Point::new(10.0, 10.0), Color::BLACK) }; - gp.freeform = Some(Freeform { points: vec![clear], ..Default::default() }); - let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); - assert!(chip.iter().all(|c| c.a() == 0), "{chip:?}"); + let chip = |opacity: f32| { + let mut gp = paint(GradientKind::Freeform, 0.0); + let point = FreeformPoint { opacity, ..FreeformPoint::new(Point::new(10.0, 10.0), Color::BLACK) }; + gp.freeform = Some(Freeform { points: vec![point], ..Default::default() }); + gradient_chip_colors(&gp, 20.0, 20.0, 4, 4) + }; + let (clear, opaque) = (chip(0.0), chip(1.0)); + assert_eq!((clear.len(), opaque.len()), (25, 25), "a color at each corner of the 4 by 4 cells"); + assert!(clear.iter().all(|c| c.a() == 0), "{clear:?}"); + assert!(opaque.iter().all(|c| *c == Color32::BLACK), "{opaque:?}"); } /// A Holographic glow's chip is clear at the corners and nearly opaque at the center; a foil's @@ -320,6 +325,7 @@ mod tests { assert!([0, 4, 20, 24].iter().all(|&i| glow[i].a() == 0), "{glow:?}"); assert!(glow[2 * 5 + 2].a() >= 240, "{glow:?}"); let foil = chip("Prism Veil"); + assert_eq!(foil.len(), glow.len(), "the same 5 by 5 corners"); assert!(foil.iter().all(|c| c.a() == 255), "{foil:?}"); } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6deacc0c01..98f7ac967d 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1753,8 +1753,8 @@ mod tests { /// the menu bar, and commands that need a value no menu item gives, with a menu path of their own /// or without one. A pick of each one it leaves /// out (with no document, one object selected or several) changes neither the document, its - /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still - /// listed. + /// selection, history and layer state, the tool's state, nor the interface. Every [`PICK_RUNS`] + /// query is still listed. #[test] fn the_palette_leaves_out_the_commands_a_pick_cannot_run() { let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); @@ -1785,16 +1785,33 @@ mod tests { (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) }); // A modeless dialog (Find and Replace) blocks nothing, so `any_dialog_open` leaves it out: the host lists it. - (doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui) + // The tool's own state: the tool, a gesture or an input method's text in progress, and an interaction the + // session holds open. + let tool = (app.session.tool_id().to_owned(), app.session.tool_composing(), app.session.pointer_held(), app.session.in_interaction()); + (doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui, tool) }; - let acts = |id: &str| { - [Session::new(), Fixture::Single.session(), Fixture::Multi.session()].into_iter().any(|session| { - let mut app = app_on(session); - let before = look(&app); - pick(&mut app, id); - look(&app) != before + // One app for each of the three cases, picked in one after another while a pick changes nothing that `look` + // sees; a pick that changes something is recorded, and its case starts again from a new app. + let fresh = |case: usize| { + app_on(match case { + 0 => Session::new(), + 1 => Fixture::Single.session(), + _ => Fixture::Multi.session(), }) }; + let mut apps: Vec = (0..3).map(fresh).collect(); + let mut acts = |id: &str| { + let mut changed = false; + for (case, app) in apps.iter_mut().enumerate() { + let before = look(app); + pick(app, id); + if look(app) != before { + changed = true; + *app = fresh(case); + } + } + changed + }; let changed: Vec<&str> = ids.iter().copied().filter(|id| acts(id)).collect(); assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); for c in &dropped { @@ -2769,4 +2786,17 @@ mod tests { } } } + + /// Smooth Bridge is part of Common Tangents (#10465): the palette lists Common Tangents once, a search for + /// "metaball" or "smooth bridge" finds it, and Smooth Bridge's own command is no result. + #[test] + fn a_search_for_metaball_finds_common_tangents_and_not_smooth_bridge() { + let app = app_on(Session::new()); + let built = built_for(&app); + assert!(built.entries.iter().all(|e| !e.ids().iter().any(|id| id == "addon.pathtools.bridge")), "Smooth Bridge is no result"); + for query in ["metaball", "smooth bridge"] { + let found = ranked(&built, query); + assert_eq!(found.first().map(String::as_str), Some(crate::addons::pathtools::COMMON_TANGENTS), "{query}: {found:?}"); + } + } } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 3ceb28ad9f..63d22da892 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -25,6 +25,9 @@ struct Window { hovered: Vec, dropped: Vec, close_requested: bool, + /// Whether the window shows on the desktop: the builder's visibility when it opened, then each + /// `Visible` command. + visible: bool, frames: usize, /// The texts its last frame drew, with their rects in the window. texts: Vec<(String, Rect)>, @@ -72,6 +75,7 @@ impl Host { ViewportCommand::OuterPosition(pos) => window.rect = Rect::from_min_size(*pos, window.rect.size()), ViewportCommand::InnerSize(size) => window.rect = Rect::from_min_size(window.rect.min, *size), ViewportCommand::CancelClose => window.close_requested = false, + ViewportCommand::Visible(visible) => window.visible = *visible, _ => {} } } @@ -91,6 +95,7 @@ impl Host { hovered: Vec::new(), dropped: Vec::new(), close_requested: false, + visible: builder.visible != Some(false), frames: 0, texts: Vec::new(), nodes: Vec::new(), @@ -572,3 +577,59 @@ fn copy_and_cut_in_a_native_window_act_on_the_art_while_another_windows_label_ha assert!(![copied, cut].concat().iter().any(|t| t == LABEL), "{what}: the floating window copied no label text"); } } + +/// A panel opened from the Window menu floats in an OS window that keeps showing while the art on +/// the canvas is selected and moved, and the Selection tool's move ends where it is released. +#[test] +fn a_window_menu_panel_stays_shown_while_art_is_selected_and_moved() { + for (command, params, panel) in + [("window.learn", json!({}), crate::panels::learn::ID), ("window.panel", json!({"panel": "imageTrace", "toggle": true}), "imageTrace")] + { + let mut h = Harness::new(); + h.app.select_tool("selection"); + h.app.ui.view.smart_guides = false; + h.app.ui.view.snap_to_point = false; + h.app.ui.view.snap_to_grid = false; + h.app.ui.view.snap_to_pixel = false; + let id = h.app.run("shape.rectangle", json!({"x": 280, "y": 180, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + h.app.run("select.none", json!({})).unwrap(); + h.app.run(command, params).unwrap(); + h.frames(4); + let viewport = h.viewport(panel); + let shown = |h: &Harness| h.host.borrow().windows.get(&viewport).is_some_and(|w| w.visible); + assert!(shown(&h), "{panel}: the window shows"); + let corner = |h: &Harness| { + let b = h.app.session.active().unwrap().doc.node(id).and_then(|n| n.geometric_bounds()).unwrap(); + (b.min_x(), b.min_y()) + }; + let before = corner(&h); + let undo = h.app.session.active().unwrap().history.undo.len(); + let view = h.app.canvas_view().expect("the canvas was drawn"); + let from = view.to_screen(vectorcraft_geom::Point::new(310.0, 205.0)); + let to = from + vec2(-40.0, 30.0); + let window = h.host.borrow().windows[&viewport].rect.translate(-ORIGIN.to_vec2()); + assert!(view.rect.contains(from) && view.rect.contains(to), "{panel}: the move stays on the canvas"); + assert!(!window.contains(from) && !window.contains(to), "{panel}: the move stays clear of the window"); + h.frame(vec![Event::PointerMoved(from), button(from, true)]); + assert!(shown(&h), "{panel}: the window shows with the art selected"); + for k in 1..=6 { + h.frame(vec![Event::PointerMoved(from + (to - from) * (k as f32 / 6.0))]); + assert!(shown(&h), "{panel}: the window shows during the move"); + } + h.frame(vec![Event::PointerMoved(to), button(to, false)]); + h.frames(3); + assert!(shown(&h), "{panel}: the window shows after the move"); + let st = h.app.session.active().unwrap(); + assert!(st.interaction.is_none(), "{panel}: no move is left open"); + assert_eq!(st.history.undo.len(), undo + 1, "{panel}: the move is one undo step"); + let (dx, dy) = (view.to_doc(to).x - view.to_doc(from).x, view.to_doc(to).y - view.to_doc(from).y); + let after = corner(&h); + assert!( + (after.0 - before.0 - dx).abs() < 0.01 && (after.1 - before.1 - dy).abs() < 0.01, + "{panel}: the art stays where it was released: moved by ({}, {}), released at ({dx}, {dy})", + after.0 - before.0, + after.1 - before.1 + ); + } +} diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 3476f5c2b0..c839b5f232 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -17,6 +17,8 @@ struct Harness { ctx: egui::Context, time: f64, nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>, + /// The node with key focus in the last frame's accessibility update. + focus: Option, shapes: Vec, } @@ -27,7 +29,7 @@ impl Harness { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); ctx.enable_accesskit(); - let mut h = Self { app, ctx, time: 0.0, nodes: Vec::new(), shapes: Vec::new() }; + let mut h = Self { app, ctx, time: 0.0, nodes: Vec::new(), focus: None, shapes: Vec::new() }; h.frames(3); h } @@ -47,7 +49,9 @@ impl Harness { /// Draw one application frame and retain its accessibility output and shapes for assertions. fn run(&mut self, input: egui::RawInput) { let out = crate::testing::app_frame(&mut self.app, &self.ctx, input); - self.nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + let update = out.platform_output.accesskit_update; + self.focus = update.as_ref().map(|update| update.focus); + self.nodes = update.map_or_else(Vec::new, |update| update.nodes); self.shapes = out.shapes; } @@ -1107,6 +1111,93 @@ fn a_docked_column_is_never_narrower_than_the_panel_minimum() { assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); } +impl Harness { + /// The node with key focus in the last frame. + fn focused_node(&self) -> Option<&egui::accesskit::Node> { + let focus = self.focus?; + self.nodes.iter().find(|(id, _)| *id == focus).map(|(_, node)| node) + } + + /// The first node named `label` in the last frame. + fn node_named(&self, label: &str) -> Option<&egui::accesskit::Node> { + self.nodes.iter().map(|(_, node)| node).find(|node| node.label() == Some(label)) + } + + /// Whether key focus is on the tab strip of a panel group: the strip or one of its tabs. + fn strip_has_focus(&self) -> bool { + use egui::accesskit::Role; + self.focused_node().is_some_and(|node| node.role() == Role::Tab && !node.label().is_some_and(|l| l.starts_with("Untitled"))) + || self.focused_node().is_some_and(|node| node.role() == Role::TabList && node.label() == Some("Panels")) + } +} + +/// The tabs of a docked group that does not fit them are reached from the keyboard through the strip's More tabs menu: +/// Tab moves key focus onto the strip, Alt+Down opens the menu with the focus on its first row, the arrow keys move +/// through its rows, Escape closes it and gives the focus back to the strip, and Enter shows the picked panel, with +/// the focus still on the strip. More tabs is announced as a button that opens a menu, expanded only while the menu is +/// open, and Alt+Down opens this menu and not the group's other menus. +#[test] +fn the_overflow_menu_of_a_docked_group_is_reached_and_used_from_the_keyboard() { + use egui::accesskit::Role; + use egui::{Key, Modifiers}; + + let mut h = Harness::new(); + let panels = + "swatches stroke color gradient character paragraph appearance align pathfinder brushes symbols transparency graphicStyles transform"; + for panel in panels.split(' ') { + h.app.run("window.panel.dock", json!({"panel": panel, "onto": "layers"})).unwrap(); + } + h.frames(3); + assert!(showing(&h.app.ui, "transform"), "the last panel docked onto the group shows"); + let more = h.node_named("More tabs").expect("the group's tabs do not fit, so the strip has a More tabs button"); + assert_eq!(more.role(), Role::Button, "More tabs is a button"); + assert_eq!(more.has_popup(), Some(egui::accesskit::HasPopup::Menu), "More tabs announces the menu it opens"); + assert_eq!(more.is_expanded(), Some(false), "More tabs starts collapsed"); + assert!(h.tab("swatches").is_none(), "Swatches is one of the tabs that do not fit"); + let expanded = |h: &Harness| h.node_named("More tabs").and_then(|node| node.is_expanded()); + let menu_focus = |h: &Harness| h.focused_node().filter(|node| node.role() == Role::MenuItem).and_then(|node| node.label()).map(str::to_owned); + + // A press inside the group gives its strip key focus; Shift+Tab leaves the strip and Tab comes back to it. + let strip = h.named("Panels", Role::TabList).expect("the group's tab strip"); + h.click(pos2(strip.center().x, strip.bottom() + 25.0)); + assert!(h.strip_has_focus(), "a press in the group focuses its strip: {:?}", h.focused_node().map(|n| (n.role(), n.label()))); + h.press(Key::Tab, Modifiers::SHIFT); + assert!(!h.strip_has_focus(), "Shift+Tab moves the focus off the strip"); + h.press(Key::Tab, Modifiers::NONE); + assert!(h.strip_has_focus(), "Tab moves the focus back onto the strip"); + + // Alt+Down opens the overflow menu, listing the tabs that do not fit, with the focus on a row. + h.press(Key::ArrowDown, Modifiers::ALT); + assert_eq!(expanded(&h), Some(true), "More tabs is expanded while its menu is open"); + let first = menu_focus(&h).expect("the focus enters the overflow menu"); + let rows: Vec<&str> = h.nodes.iter().filter(|(_, n)| n.role() == Role::MenuItem).filter_map(|(_, n)| n.label()).collect(); + assert!(rows.contains(&"Swatches"), "the menu lists a tab that does not fit: {rows:?}"); + assert!(first != "Transform" && h.tab(&first).is_none(), "the focused row names a panel whose tab does not fit: {first}"); + h.press(Key::ArrowDown, Modifiers::NONE); + let second = menu_focus(&h).expect("the focus stays in the menu"); + assert_ne!(second, first, "Down moves the focus to the next row"); + h.press(Key::ArrowUp, Modifiers::NONE); + assert_eq!(menu_focus(&h).as_deref(), Some(first.as_str()), "Up moves it back"); + + // Escape closes the menu and gives the focus back to the strip, with the shown panel unchanged. + h.press(Key::Escape, Modifiers::NONE); + assert_eq!(expanded(&h), Some(false), "Escape closes the overflow menu"); + assert!(h.strip_has_focus(), "Escape gives the focus back to the strip"); + assert!(showing(&h.app.ui, "transform"), "Escape picks nothing"); + + // Enter on a row shows that panel; its tab is drawn and selected, and the focus stays on the strip. + h.press(Key::ArrowDown, Modifiers::ALT); + h.press(Key::ArrowDown, Modifiers::NONE); + let picked = menu_focus(&h).expect("a row has the focus"); + h.press(Key::Enter, Modifiers::NONE); + h.frames(1); + assert_eq!(expanded(&h), Some(false), "Enter closes the overflow menu"); + assert!(!showing(&h.app.ui, "transform"), "the picked panel replaces Transform"); + let tab = h.nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::Tab && n.label() == Some(picked.as_str())); + assert_eq!(tab.and_then(|n| n.is_selected()), Some(true), "the picked panel's tab, {picked}, is drawn and selected"); + assert!(h.strip_has_focus(), "the focus stays on the strip after the pick"); +} + /// A tab group dragged out of the icon column by its grip floats as an expanded panel: its tabs show /// in the window, and a click on each tab shows that panel. #[test] diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 0ac94e9875..013b0b781b 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -155,13 +155,17 @@ pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) } /// The Corner select of a live rectangle whose corners share one radius field: the kind of all -/// four corners, also while some of them are Direct-Selected, blank when they differ. A pick sets -/// it on every corner of each selected live rectangle ([`set_rectangle_kinds`]). +/// four corners, also while some of them are Direct-Selected, blank when they differ. It is one +/// number cell wide, as the Corner Radius field above it is. A pick sets it on every corner of each +/// selected live rectangle ([`set_rectangle_kinds`]). fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { let Some(lc) = LiveCorners::of(n) else { return }; let entries = corner_entries(); - let current = lc.style(&lc.all()).1; - let picked = Field::new(tl!("Corner")).show(ui, |ui, _| corner_select(ui, tl!("Corner"), current, &entries)).inner.flatten(); + let current = lc.style(&lc.all()).1.map_or(Mixed::Mixed, Mixed::Same); + let picked = Field::new(tl!("Corner")) + .show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(current), &entries).number_cell().show(ui).events.committed().copied()) + .inner + .flatten(); if let Some(kind) = picked { set_rectangle_kinds(app, kind, None); } @@ -681,13 +685,35 @@ pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, match pstate::>(ctx, "proxy-mixed") { Some((k, mixed)) if k == key => mixed, _ => { - let mixed = app.session.proxy_mixed(); + let mixed = walk_mixed_paints(app); set_pstate(ctx, "proxy-mixed", Some((key, mixed))); mixed } } } +/// [`mixed_paints`] for readers without a `Ui`, such as the panel menus' states: from the same cache while the app +/// has its interface context, else from a walk of the selection. +pub(crate) fn mixed_paints_now(app: &VectorcraftApp) -> (bool, bool) { + match &app.ui_ctx { + Some(ctx) => mixed_paints(app, ctx), + None => walk_mixed_paints(app), + } +} + +/// [`vectorcraft_engine::Session::proxy_mixed`], which walks the selection. +fn walk_mixed_paints(app: &VectorcraftApp) -> (bool, bool) { + #[cfg(test)] + MIXED_PAINT_WALKS.set(MIXED_PAINT_WALKS.get() + 1); + app.session.proxy_mixed() +} + +#[cfg(test)] +thread_local! { + /// How many times [`walk_mixed_paints`] walked the selection on this thread. + pub(crate) static MIXED_PAINT_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The stroke the Stroke panel, Control bar and Properties show: while the Type tool edits text, /// the selected characters' stroke, else [`vectorcraft_engine::Session::shown_stroke`]. pub(crate) fn current_stroke(app: &VectorcraftApp) -> Option { @@ -1108,6 +1134,31 @@ pub(crate) fn popover_body(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) - mod tests { use super::*; + /// The panel menus' states (the Color and Color Wheel menus) read whether the fill and stroke differ from the + /// proxies' cache: one walk of the selection for each revision, which the proxies read too. + #[test] + fn panel_menu_states_walk_the_mixed_paints_once_per_revision() { + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + for x in [10, 60, 110] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + let walks = || MIXED_PAINT_WALKS.get(); + let start = walks(); + let mut states = CommandStates::new(); + panel_menu_states(&app, &mut states); + assert_eq!(walks(), start + 1, "the menus walk the selection once"); + panel_menu_states(&app, &mut states); + assert_eq!(mixed_paints(&app, &ctx), (false, false)); + assert_eq!(walks(), start + 1, "the same revision is not walked again, by the menus or the proxies"); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + panel_menu_states(&app, &mut states); + assert_eq!(walks(), start + 2, "an edit is walked again"); + } + #[test] fn proxy_events_run_their_commands() { let ran = |activated, double, swap, defaults| -> Vec<(&'static str, Value)> { proxy_commands(activated, double, swap, defaults) }; diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index 1fe2f13711..acaba32fe0 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -927,8 +927,10 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { // The View menu's proof items change the whole process's proof view. let _view = crate::testing::DefaultProofView::new(); + // A new app for each item, all in one window. + let window = crate::testing::window_context(); for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { - let (mut app, _) = app_with_three_moves(); + let (mut app, _) = three_moves_in(new_app_in(&window)); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); let held = steps(&app, 0, 0)[3].1.clone(); let start = app.session.journal.len(); @@ -1342,3 +1344,17 @@ fn insert_select_object_refuses_bad_params_and_changes_nothing() { } assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in"); } + +/// The panel menu's Reset Actions asks in the dialog whose `key` the params text of [`RESET`] names, as `ui.inspect` +/// lists it. +#[test] +fn reset_params_text_names_the_question_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == RESET).expect("registered").3; + let mut app = new_app(); + edits::ask_reset(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "actionsQuestion"); + assert!(doc.contains(&format!("dialog `{key}`")), "Reset Actions opens `{key}`, which the params text of {RESET} does not name"); +} diff --git a/crates/ui-egui/src/panels/actions/tests_files.rs b/crates/ui-egui/src/panels/actions/tests_files.rs index a88cbc36fe..396c3d6af9 100644 --- a/crates/ui-egui/src/panels/actions/tests_files.rs +++ b/crates/ui-egui/src/panels/actions/tests_files.rs @@ -53,12 +53,24 @@ fn browser_picks_load_and_replace_action_sets_without_a_file_reader() { } } +/// Each built-in action plays on a selection it applies to (text for Outline Text, two +/// overlapping rectangles otherwise) and edits the drawing, so its commands and their +/// parameters are ones the engine accepts. #[test] -fn defaults_are_valid_commands() { - for a in default_sets().actions { - for step in a.steps { - assert!(vectorcraft_engine::find_command(&step.command).is_some(), "{}", step.command); - } +fn built_in_actions_play_and_edit_the_drawing() { + for (idx, a) in default_sets().actions.iter().enumerate() { + let mut app = new_app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ids: Vec = if a.steps.iter().any(|s| s.command.starts_with("type.")) { + vec![app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab"})).unwrap()["id"].clone()] + } else { + [10, 30].iter().map(|x| app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone()).collect() + }; + app.run("select.set", json!({ "ids": ids })).unwrap(); + app.ui.actions = default_list(); + let before = undo_steps(&app); + play(&mut app, 0, idx).unwrap_or_else(|e| panic!("{}: {e}", a.name)); + assert!(undo_steps(&app) > before, "{} edits the drawing", a.name); } } diff --git a/crates/ui-egui/src/panels/actions/tests_playback.rs b/crates/ui-egui/src/panels/actions/tests_playback.rs index f566eb22fc..d81c005ef1 100644 --- a/crates/ui-egui/src/panels/actions/tests_playback.rs +++ b/crates/ui-egui/src/panels/actions/tests_playback.rs @@ -89,7 +89,9 @@ fn actions_play_on_the_artboard_active_when_they_play() { app.ui.actions.push(Action { set, ..Action::new(name, steps) }).unwrap(); set_actions(app, 0).len() - 1 }; + app.view_mut().unwrap().artboard = 1; app.run("edit.copy", json!({})).unwrap(); + app.view_mut().unwrap().artboard = 0; let align = record(&mut app, "Align Left", "object.align", json!({"horizontal": "left", "to": "artboard"})); assert_eq!(bounds(&app, &[rect]).x0, boards[0].x0, "aligned to artboard 0 while recording"); let paste = record(&mut app, "Paste in Place", "edit.pasteInPlace", json!({})); diff --git a/crates/ui-egui/src/panels/actions/tests_support.rs b/crates/ui-egui/src/panels/actions/tests_support.rs index 610e180bf0..3f763ad877 100644 --- a/crates/ui-egui/src/panels/actions/tests_support.rs +++ b/crates/ui-egui/src/panels/actions/tests_support.rs @@ -20,9 +20,14 @@ use crate::VectorcraftApp; /// An app with the built-in set, in a window whose dialog host the tests drive and which has drawn its first frame, so /// the window's keymap holds the app's commands. pub(crate) fn new_app() -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - let ctx = app.ui_ctx.clone().expect("a window"); - crate::testing::app_frame(&mut app, &ctx, Default::default()); + new_app_in(&crate::testing::window_context()) +} + +/// [`new_app`] in the window of `ctx` ([`crate::testing::window_context`]), which a test can reuse for a new app at +/// each step. +pub(crate) fn new_app_in(ctx: &egui::Context) -> VectorcraftApp { + let mut app = crate::testing::windowed_in(VectorcraftApp::new(Session::new(), Default::default()), ctx); + crate::testing::app_frame(&mut app, ctx, Default::default()); app } @@ -251,7 +256,11 @@ pub(crate) fn cancel_dialog(app: &mut VectorcraftApp) { /// A document with one rectangle selected and the set "Moves" with one action that moves it /// right three times, by 1, 2 and 4 pt → (the app, the rectangle's left edge as it moves). pub(crate) fn app_with_three_moves() -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) { - let mut app = new_app(); + three_moves_in(new_app()) +} + +/// [`app_with_three_moves`] made from `app`, a new app such as [`new_app_in`] gives. +pub(crate) fn three_moves_in(mut app: VectorcraftApp) -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) { app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let id = vectorcraft_doc::NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 5e5a4fc5b4..0ca5b4caf2 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -23,6 +23,21 @@ fn picked(panel: &Panel) -> (Vec, Option, Option) { (s.items.clone(), s.lead, s.anchor) } +/// Every footer action is announced as a button named by its label, and none announces a pressed state: they are +/// plain actions. Add New Effect announces the menu it opens. +#[test] +fn the_footer_actions_are_buttons_without_a_pressed_state() { + use craft::ui::contract::{PopupKind, Role}; + + let panel = Panel::new(app_with_a_selected_rectangle(), show); + for name in ["Add New Stroke", "Add New Fill", "Add New Effect", "Delete Selected Item", "Duplicate Selected Item", "Clear Appearance"] { + assert!(panel.shows_role(name, Role::BUTTON), "{name} is a button"); + assert_eq!(panel.toggled(name), None, "{name} announces no pressed state"); + } + assert_eq!(panel.popup_kind("Add New Effect"), Some(PopupKind::Menu)); + assert_eq!(panel.popup_kind("Clear Appearance"), None); +} + /// Duplicating rows picks the copies, each right above its original, as the Layers panel does: /// the active row's copy becomes active, the anchor's copy the anchor. #[test] diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 048d8dcfb0..26828a967d 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -34,8 +34,8 @@ use craft::theme::Variant; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::contract::{ - Bind, CollectionEvent, Entry, Props as _, RowAlign, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, clicked, - request_rename, + Bind, CollectionEvent, Entry, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, + clicked, request_rename, }; use craft::ui::dialog::StackDialog as _; use craft::ui::display::{Divider, Shade, Text}; @@ -524,13 +524,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (selection, saving) = (&mut model.selection, &mut model.saving); let (mut export_clicked, mut footer, mut screens) = (false, None, false); // The grid takes the room the settings, Export and the footer bar leave. + // The settings scroll in at most half the panel's height, so a long list of format rows stays reachable. + // The preset name row stays below them, in view when Save As Preset opens it. + let settings_room = ui.available_height() / 2.0; + let settings_id = ui.scope_id().with(("asset-export-settings", uid)); let footed = Stack::new().fill().footer(|ui, _| { - crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| { - let (change, files_each) = settings(ui, st); - (seen.change, seen.files_each) = (change, files_each); - seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all)); - seen.save = save_row(ui, saving); - }); + Stack::new().id(settings_id).label(tl!("Export Settings")).fill_width().scroll(Scroll::vertical()).room_height(settings_room).show( + ui, + |ui, _| { + crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| { + let (change, files_each) = settings(ui, st); + (seen.change, seen.files_each) = (change, files_each); + seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all)); + }); + }, + ); + seen.save = save_row(ui, saving); Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| { let label = if shown_sel.is_empty() || shown_sel.len() == all.len() { tl!("Export").to_string() diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index d8075d4c66..aaccca637b 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.brush_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Rc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect() } diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 9415a7e50f..677eec516a 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -6,7 +6,6 @@ use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use std::sync::{Arc, Mutex, Weak}; -use std::time::SystemTime; // PLAN: assumed the framework paths below (craft::text::ui re-exports, craft_ui widgets and runtime, craft::font_manager). use craft::behavior::EditEvent; @@ -47,12 +46,15 @@ use crate::font_menu; /// attributes of the paragraph the selection starts in (else of the first paragraph). /// Font/paragraph controls and named-style capture use this; dimensional fields use `shared_effective`. pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft_doc::ParaStyle)> { + let state = app.session.active()?; + // Hover changes the canvas, but the picker compares its next row click against the committed font. + let doc = state.interaction.as_ref().filter(|_| app.font_preview_owner.is_some()).map_or(&state.doc, |preview| &preview.doc); if let Some((id, a, b)) = text_editing(app) - && let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind) + && let Some(NodeKind::Text(t)) = doc.node(id).map(|n| &n.kind) { return Some((vectorcraft_text::edit::insertion_style(&t.runs, a, b), t.para_at(t.paragraphs_in(a, a).start).clone())); } - let t = first_selected_text(app)?; + let NodeKind::Text(t) = &first_selected_text_node_in(state, doc)?.kind else { return None }; Some((t.first_style(), t.para_at(0).clone())) } @@ -68,7 +70,11 @@ pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_d /// their descendants, in selection order, then paint order within each selected object. pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> { let st = app.session.active()?; - for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + first_selected_text_node_in(st, &st.doc) +} + +fn first_selected_text_node_in<'a>(state: &DocState, doc: &'a vectorcraft_doc::Document) -> Option<&'a vectorcraft_doc::Node> { + for node in state.selection.objects.iter().filter_map(|id| doc.node(*id)) { let mut text = None; node.walk(&mut |n| { if text.is_none() && matches!(n.kind, NodeKind::Text(_)) { @@ -1219,16 +1225,14 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow let languages: Option> = rows.contains(CharacterRows::STYLE_TOGGLES).then(|| LANGUAGES.iter().map(|(name, _, _)| (name.to_string(), name.to_string())).collect()); let catalog = vectorcraft_text::FontDb::global().catalog(); - let before = font_menu::picker_settings(app); - let mut settings = before.clone(); - let document = font_menu::document_family_set(app); - let recent = font_menu::recently_added_set(app, SystemTime::now()); - let sets = font_menu::family_sets(Some(&document[..]), &recent[..]); + let mut hold = font_menu::hold(app); + let before = hold.settings.clone(); + let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added); let sample = font_menu::sample_text(app); let unit = type_unit(app); let mut source = FontPickerSource::new(catalog) - .settings(Bind::bound(&mut settings)) - .filters(Bind::bound(&mut app.ui.font_filters)) + .settings(Bind::bound(&mut hold.settings)) + .filters(Bind::bound(&mut hold.filters)) .sets(&sets) .scripts(&FontScript::ALL) .filter_layout(FilterLayout::Toolbar); @@ -1248,7 +1252,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow controls = controls.axes(FaceAxes::new(axes, instances).italic(face_of(¤t.font_style).2)); } let out = controls.show(ui); - font_menu::store_picker_settings(app, &before, settings); + hold.store(app, &before); let CharacterControlsOutput { picker, preview_family, edits, .. } = out; if let Some(owner) = picker { font_menu::apply_preview(app, owner, preview_family); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 6713eb3033..d1f6be332e 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -7,6 +7,18 @@ use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; use vectorcraft_engine::Session; +/// The different values in `items`, in the order they first appear: `[v]` when every item is `v`, +/// and empty when there are no items. +fn distinct(items: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for item in items { + if !out.contains(&item) { + out.push(item); + } + } + out +} + /// `value` is `want` (the panel's fields are single precision). fn near(value: Option, want: f64) -> bool { value.is_some_and(|v| (f64::from(v) - want).abs() < 1e-6) @@ -844,14 +856,16 @@ fn underline_command_underlines_a_mixed_selection() { let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap(); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "underline": true})).unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); + // The underlined characters, in order. let underlined = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.underline).collect::>(), + NodeKind::Text(t) => t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect::(), _ => panic!("text"), }; + assert_eq!(underlined(&app), "A"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(true))); - assert!(underlined(&app).iter().all(|u| *u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), "AB"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(false))); - assert!(underlined(&app).iter().all(|u| !*u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), ""); } /// At a caret in text the Type tool edits, with no characters selected, the Character @@ -902,15 +916,15 @@ fn kashidas_menu_item_handles_default_and_mixed_ranges() { assert!(!state(&app, &row).1); fire(&mut app, &row); assert!(state(&app, &row).1); - let kashidas = |app: &VectorcraftApp| story_frame(app, id).runs.iter().map(|r| r.style.kashidas).collect::>(); - assert!(kashidas(&app).iter().all(|v| *v)); + let kashidas = |app: &VectorcraftApp| distinct(story_frame(app, id).runs.iter().map(|r| r.style.kashidas)); + assert_eq!(kashidas(&app), [true]); app.select_tool("type"); app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); assert!(!state(&app, &row).0, "disabled at an empty caret"); // The result is not the point: a disabled row must leave the text as it was. let _ = run(&mut app, &row.id, &row.params); - assert!(kashidas(&app).iter().all(|v| *v), "an empty caret leaves all characters unchanged"); + assert_eq!(kashidas(&app), [true], "an empty caret leaves all characters unchanged"); } /// Reset Panel sets every character attribute the panel shows, except the font family, style @@ -1112,7 +1126,7 @@ fn select_all_in_threaded_text_formats_and_copies_the_whole_story() { crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap(); for id in [a, b] { let t = frame(&app, id); - assert!(t.runs.iter().all(|r| (r.style.size - 9.0).abs() < 1e-9), "every character of frame {id} is 9 pt"); + assert_eq!(distinct(t.runs.iter().map(|r| r.style.size)), [9.0], "every character of frame {id} is 9 pt"); assert!((t.para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id}'s paragraphs take the space"); } assert!(intercept_text_command(&mut app, "edit.copy").is_some()); @@ -1174,9 +1188,9 @@ fn story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_lea assert_eq!(text_story(&app), Some(vec![NodeId(b), NodeId(c)])); format(&mut app, json!({"size": 9})); - assert!(story_sizes(&app, a).iter().all(|s| (*s - 12.0).abs() < 1e-9), "the frame that left keeps its size"); + assert_eq!(distinct(story_sizes(&app, a)), [12.0], "the frame that left keeps its size"); for id in [b, c] { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } } @@ -1262,26 +1276,28 @@ fn selection_tool_changes_reach_every_frame_of_the_story() { style(&mut app, json!({"size": 9})); assert_eq!(undo_steps(&app), steps + 1, "one undo step"); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } - assert!(story_sizes(&app, other).iter().all(|s| (*s - 12.0).abs() < 1e-9), "other type keeps its size"); + assert_eq!(distinct(story_sizes(&app, other)), [12.0], "other type keeps its size"); app.run("edit.undo", json!({})).unwrap(); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 12.0).abs() < 1e-9), "undo gives frame {id} its size back"); + assert_eq!(distinct(story_sizes(&app, id)), [12.0], "undo gives frame {id} its size back"); } format(&mut app, json!({"underline": true})); + let underline = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.underline)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| r.style.underline), "frame {id} is underlined"); + assert_eq!(underline(&app, id), [true], "frame {id} is underlined"); } - assert!(story_frame(&app, other).runs.iter().all(|r| !r.style.underline)); + assert_eq!(underline(&app, other), [false]); // Tate-chu-yoko Settings and Warichu Settings set their values through `run_format`. run_format(&mut app, json!({"tcyUpDown": 2})).unwrap(); + let up_down = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.tcy_up_down)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| (r.style.tcy_up_down - 2.0).abs() < 1e-9), "frame {id} takes Up/Down"); + assert_eq!(up_down(&app, id), [2.0], "frame {id} takes Up/Down"); } - assert!(story_frame(&app, other).runs.iter().all(|r| r.style.tcy_up_down.abs() < 1e-9)); + assert_eq!(up_down(&app, other), [0.0]); } /// The fields show a value only when every frame of the selected story has it: a hidden frame that diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 6208c22cb3..ba0c6cf7a3 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -314,14 +314,14 @@ fn target(app: &VectorcraftApp, ui: &Ui) -> Target { target_with(app, super::active_mixed(app, ui.ctx())) } -/// Whether the active proxy is "?", read from the session (the panel reads its per-frame cache). +/// Whether the active proxy is "?", from the proxies' cache ([`super::mixed_paints_now`]). fn mixed_now(app: &VectorcraftApp) -> bool { - let (fill, stroke) = app.session.proxy_mixed(); + let (fill, stroke) = super::mixed_paints_now(app); if app.session.fill_active { fill } else { stroke } } /// [`target`] with `mixed` for a "?" active proxy: the panel reads it from its per-frame cache, -/// `ui.colorPanel` from the session. +/// `ui.colorPanel` and the panel menus through [`mixed_now`]. fn target_with(app: &VectorcraftApp, mixed: bool) -> Target { if mixed { return Target::Paint(None, None); @@ -440,7 +440,7 @@ pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) { apply_with(app, &tgt, out); } -/// [`target`] with the session's "?" state, for callers without the panel's pass. +/// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass. pub(crate) fn target_now(app: &VectorcraftApp) -> Target { target_with(app, mixed_now(app)) } @@ -616,8 +616,9 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { /// The checks, titles and enabled states of [`menu_rows`]: the mode the panel shows is checked, and /// the rows that need a colour are off without one. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { - let tgt = target_now(app); - let has_color = tgt.color().is_some() || mixed_now(app); + let mixed = mixed_now(app); + let tgt = target_with(app, mixed); + let has_color = tgt.color().is_some() || mixed; for (command, state) in ColorPanelMenu::states(LAYOUT, &app.ui.color_panel, &shown(app, &tgt), has_color) { let state = if command == ColorPanelCommand::NewSwatch && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state }; states.set(command, state); diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 3d1b32f037..7ba34fe65a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -10,7 +10,7 @@ // framework crates' layout (racheck-fw); none of them is imported anywhere else in the app yet. use std::borrow::Cow; -use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange}; +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ColorPanelMode, HarmonyWheel}; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; @@ -19,7 +19,7 @@ use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; @@ -592,44 +592,45 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else if rows.is_empty() { Notice::new(Tone::Neutral, tl!("No matches.")).show(ui); } else { - let names: Vec = rows.iter().map(|(n, _)| n.clone()).collect(); - let mut selection = app - .ui - .color_themes_panel - .picked - .as_ref() - .and_then(|p| names.iter().position(|n| n == p)) - .map_or_else(Selection::default, Selection::single); - let out = List::new(tl!("My Themes")).select(craft::ui::contract::SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( - ui, - &Names(&names), - &mut |key, _| { - let colors = rows.get(*key).map(|(_, c)| c.clone()).unwrap_or_default(); - let name = names.get(*key).cloned().unwrap_or_default(); - ListRow::new(name).thumb(ThumbSize::Small, move |cx, rect| { + let document = app.session.active().map(|st| st.uid); + let selection = picked(app).map_or_else(Selection::default, Selection::single); + let out = List::new(tl!("My Themes")) + .id(ui.scope_id().with(("my-themes", document))) + .select(craft::ui::contract::SelectMode::Single) + .selection(Bind::given(selection)) + .row_menu() + .show_items(ui, &keyed(&rows, |(name, _)| name.clone()), &mut |name, icx| { + let colors = rows[icx.at].1.clone(); + ListRow::new(name.clone()).thumb(ThumbSize::Small, move |cx, rect| { let w = rect.width() / colors.len().max(1) as f32; cx.data_shapes(colors.iter().enumerate().map(|(i, c)| { egui::Shape::rect_filled(Rect::from_min_size(rect.min + vec2(i as f32 * w, 0.0), vec2(w, rect.height())), 0.0, c32(c)) })); }) - }, - ); + }); for event in out.events { match event { CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { - if let Some(name) = keys.last().and_then(|k| names.get(*k)) { - app.ui.color_themes_panel.picked = Some(name.clone()); - } + app.ui.color_themes_panel.picked = keys.last().cloned(); } + CollectionEvent::ContextMenu(request) => app.ui.color_themes_panel.picked = Some(request.key), // Enter and a double click edit the theme. - CollectionEvent::Activate(key) => { - if let Some(name) = names.get(key) { - edit_saved(app, name); - } - } + CollectionEvent::Activate(name) => edit_saved(app, &name), _ => {} } } + if let Some(request) = out.menu + && app.ui.color_themes_panel.tab == MY_THEMES + && app.ui.color_themes_panel.picked.as_ref() == Some(&request.key) + { + Menu::context(request.key, &out.response).show(ui, |ui, _| { + for (id, label) in [(EDIT, tl!("Edit Theme")), (ADD_TO_SWATCHES, tl!("Add to Swatches")), (DELETE, tl!("Delete Theme"))] { + if MenuItem::new(label).enabled(enabled(app, id)).show(ui).ran { + run(app, id, &Value::Null); + } + } + }); + } } let labels = vec![Label::from(tl!("Delete theme")), Label::from(tl!("Add to Swatches")), Label::from(tl!("Edit theme"))]; footer(app, ui, &[DELETE, ADD_TO_SWATCHES, EDIT], &["trash-2", "dc-folder", "pencil"], labels); @@ -831,6 +832,57 @@ mod tests { assert_eq!(picked(&app), None); } + #[test] + fn the_theme_menu_follows_its_row_when_the_list_is_filtered() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + app.ui.color_themes_panel.picked = Some("Forest".into()); + let mut panel = Panel::new(app, show); + panel.secondary_click("Harvest"); + assert_eq!(picked(&panel.app()).as_deref(), Some("Harvest")); + panel.app().ui.color_themes_panel.find = "vest".into(); + panel.frame(); + panel.click_menu_item("Delete Theme"); + assert_eq!(themes(&panel.app()).iter().map(|t| t.name.as_str()).collect::>(), ["Harbor", "Forest"]); + } + + #[test] + fn keyboard_theme_menu_uses_the_focused_row_without_a_document() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + assert!(app.session.close_document(0)); + let mut panel = Panel::new(app, show); + panel.click("Forest"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Edit Theme")); + assert!(panel.menu_item_enabled("Delete Theme")); + assert!(!panel.menu_item_enabled("Add to Swatches")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + assert!(panel.focused("Forest")); + } + + #[test] + fn the_theme_menu_closes_when_its_row_disappears_or_the_document_changes() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(three_themes(""), show); + panel.secondary_click("Harbor"); + assert!(panel.menu_item_enabled("Edit Theme")); + panel.app().ui.color_themes_panel.find = "Forest".into(); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + panel.secondary_click("Forest"); + assert!(panel.menu_item_enabled("Add to Swatches")); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Add to Swatches", Role::MENU_ITEM)); + } + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in /// the name, in their saved order; it reads names only, and its text is plain text. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 3e706b06c1..23d6d345d8 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -334,9 +334,11 @@ fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result Option { - serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v)) + let saved = serde_json::from_value(v.clone()).ok().filter(vectorcraft_engine::cmd::color_is_finite); + saved.or_else(|| vectorcraft_engine::cmd::color_value(v)) } fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { @@ -618,14 +620,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { /// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let srgb = cms::active().rgb_is_srgb(); - for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) { + let color = target_now(app).color(); + for item in items(&app.ui.color_wheel, srgb, color) { let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked); if let Some(hint) = item.hint { state = state.hint(hint); } states.set(CommandRef::new(row_id(&item.id)), state); } - let has_color = target_now(app).color().is_some(); + let has_color = color.is_some(); for (notation, label) in copy_notations() { let oklch = notation == "oklch"; let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch)); diff --git a/crates/ui-egui/src/panels/discover.rs b/crates/ui-egui/src/panels/discover.rs index 649727d609..58c9bb5c12 100644 --- a/crates/ui-egui/src/panels/discover.rs +++ b/crates/ui-egui/src/panels/discover.rs @@ -52,7 +52,12 @@ pub struct View { /// The text of a tool's shortcut in the window's keymap, empty when it has none. fn tool_shortcut(app: &VectorcraftApp, id: &str) -> String { - menus::shortcut_of(app, &format!("tool:{id}")).map_or_else(String::new, |chord| chord.display(crate::keymap::platform())) + tool_shortcut_in(&menus::command_shortcuts(app), id) +} + +/// [`tool_shortcut`] looked up in `chord` ([`menus::command_shortcuts`]). +fn tool_shortcut_in(chord: &dyn Fn(&craft::keymap::CommandRef) -> Option, id: &str) -> String { + chord(&crate::keymap::command_of(&format!("tool:{id}"))).map_or_else(String::new, |chord| chord.display(crate::keymap::platform())) } /// Updates the retained results' labels, menu paths and shortcuts after the menu state changes (a @@ -109,6 +114,7 @@ fn refresh(app: &mut VectorcraftApp) { /// The tools, each with the entry the search ranks it by. fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> { let lang = crate::i18n::current(); + let chord = menus::command_shortcuts(app); vectorcraft_tools::catalog::all_tools() .map(|tool| { let label: String = crate::i18n::tr(lang, tool.label).into(); @@ -120,7 +126,7 @@ fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> { id: tool.id.into(), label, path: vec![], - shortcut: tool_shortcut(app, tool.id), + shortcut: tool_shortcut_in(&chord, tool.id), english_label: tool.label.into(), english_path: vec![], params: Value::Null, diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 5cb45f666a..13749667b9 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -950,7 +950,7 @@ mod tests { app.canvas.doc_info.clone().unwrap().1 }; let all = shown(&mut app, ""); - assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]); + assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]); assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result"); for category in ["document", "fonts"] { let other = shown(&mut app, category); diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index e639ae3ea4..ad1bc48c1f 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -15,6 +15,8 @@ //! as one of its alternates in its word. A glyph no feature reaches whose name does not belong to //! another letter is applied as a glyph choice, which may not join. Other glyphs are drawn dimmed, //! and their notes say why they cannot be applied to the selection. +//! A right-click on a character offers Insert Glyph. A right-click on a glyph without a +//! character offers Apply Alternate. Both use the same text target as double-click or Enter. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`menu_rows`]). //! After the framework's categories, the Show menu lists the OpenType categories the browsed font @@ -22,12 +24,13 @@ //! as Entire Font shows them. use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; -use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsWords}; +use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; use craft::keymap::CommandRef; -use craft::ui::contract::Bind; -use craft::ui::menu::PanelRow; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Env; use egui::{Color32, ColorImage, Ui}; @@ -297,11 +300,11 @@ fn insert(app: &mut VectorcraftApp, ch: char) -> bool { /// character, all read when it is made, so it borrows nothing from the app. Every method uses the /// held face whatever family and style it is given: the face of the canvas row or of the selected /// text can be an instance of variable axes that no family and style name reaches. -pub(crate) struct VcGlyphs<'a> { - db: &'a FontDb, +pub(crate) struct VcGlyphs { family: String, style: String, face: Option>, + revision: u64, /// What a glyph no character maps can do to the selected character; none for a face without one /// and in Alternates for Selection. fit: Option, @@ -311,7 +314,7 @@ pub(crate) struct VcGlyphs<'a> { empty: Option, } -impl VcGlyphs<'static> { +impl VcGlyphs { /// The source of the panel: the browsed face, or the face of the selected character's alternates /// in Alternates for Selection. pub(crate) fn of(app: &mut VectorcraftApp) -> Self { @@ -319,44 +322,42 @@ impl VcGlyphs<'static> { if app.ui.glyphs_panel.category == ALTERNATES { return match alternates_listing(app) { Ok(listing) => VcGlyphs { - db: FontDb::global(), family: listing.face.family.clone(), style: listing.face.style.clone(), face: Some(listing.face.clone()), + revision: listing.revision(), fit: None, listing: Some(listing), empty: None, }, - Err(note) => VcGlyphs { db: FontDb::global(), family, style, face: None, fit: None, listing: None, empty: Some(note) }, + Err(note) => VcGlyphs { family, style, face: None, revision: 0, fit: None, listing: None, empty: Some(note) }, }; } let fit = face.as_ref().map(|f| Fit::of(app, f)); let empty = face.is_none().then(|| tl!("No fonts are available.").to_string()); - VcGlyphs { db: FontDb::global(), family, style, face, fit, listing: None, empty } + let revision = face.as_ref().map_or(0, |face| u64::from(face.id())); + VcGlyphs { family, style, face, revision, fit, listing: None, empty } } /// The source of `face` alone: it draws glyphs and describes nothing about the selection. fn bare(face: Arc) -> Self { VcGlyphs { - db: FontDb::global(), family: face.family.clone(), style: face.style.clone(), + revision: u64::from(face.id()), face: Some(face), fit: None, listing: None, empty: None, } } -} - -impl VcGlyphs<'_> { /// The family and style the panel shows. fn font(&self) -> (&str, &str) { (&self.family, &self.style) } } -impl GlyphSource for VcGlyphs<'_> { +impl GlyphSource for VcGlyphs { fn cells(&self, _family: &str, _style: &str, category: &str) -> Vec { let Some(face) = &self.face else { return vec![] }; if category == ALTERNATES { @@ -396,7 +397,9 @@ impl GlyphSource for VcGlyphs<'_> { } fn revision(&self) -> u64 { - self.db.generation() + // The grid uses this for both cached cells and open glyph-ID menus. Changes + // elsewhere in the font catalog leave the displayed face and its glyph IDs valid. + self.revision } fn categories(&self, _family: &str, _style: &str) -> Vec<(String, String)> { @@ -483,7 +486,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - if let Some(cell) = out.activated { + let menu_cell = out.menu.as_ref().filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)).map(|menu| menu.cell); + if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } if let Some(pick) = out.alternate { @@ -491,6 +495,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Offer the action for the clicked cell using the grid's face and text context for this pass. +fn cell_menu(ui: &mut Ui, source: &VcGlyphs, can_insert: bool, menu: &GlyphCellMenu) -> bool { + let Some(face) = &source.face else { return false }; + let (label, enabled) = match menu.cell { + GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), + GlyphCell::Glyph(gid) => { + let applies = match &source.listing { + Some(listing) => listing.variants.iter().any(|variant| variant.gid == gid), + None => source.fit.as_ref().is_some_and(|fit| fit.pick(face, gid).is_some()), + }; + (tl!("Apply Alternate"), applies) + } + _ => return false, + }; + Menu::context(label, &menu.opener).show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran).inner.unwrap_or(false) +} + /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation /// form), or put the glyph on the selected character. pub(crate) fn activate(app: &mut VectorcraftApp, cell: GlyphCell) { @@ -621,6 +642,17 @@ struct Listing { } impl Listing { + /// The visible alternates can change at another text target in the same face. + fn revision(&self) -> u64 { + let mut revision = DefaultHasher::new(); + (self.face.id(), self.id, self.bytes, self.variants.len()).hash(&mut revision); + for variant in &self.variants { + variant.gid.hash(&mut revision); + } + // Face-only revisions are u32 IDs. Keep a listing in a separate range. + revision.finish() | (1 << 63) + } + /// Draw the character with glyph `gid` of the listing, as one undo step. fn apply(&self, app: &mut VectorcraftApp, gid: u32) { if let Some(variant) = self.variants.iter().find(|v| v.gid == gid) { @@ -748,7 +780,7 @@ impl OnCanvas { } /// The source that draws the offered glyphs ([`Self::face`]). - pub fn source(&self) -> VcGlyphs<'static> { + pub fn source(&self) -> VcGlyphs { VcGlyphs::bare(self.face.clone()) } diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..b438a904ec 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -43,7 +43,7 @@ fn browsed(app: &VectorcraftApp) -> (String, String) { } /// The panel's cell source, as the panel builds it. -fn source(app: &mut VectorcraftApp) -> VcGlyphs<'static> { +fn source(app: &mut VectorcraftApp) -> VcGlyphs { VcGlyphs::of(app) } @@ -208,9 +208,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert!(!rows(&app).contains(&form_ref(GlyphForm::Jis78)), "hidden without Show East Asian Options"); app.session.prefs.show_east_asian_options = true; let shown = rows(&app); - for form in GlyphForm::ALL { - assert!(shown.contains(&form_ref(form)), "{form:?} in {shown:?}"); - } + assert!(shown.contains(&form_ref(GlyphForm::Jis78)), "shown with Show East Asian Options: {shown:?}"); const FAMILY: &str = "BIZ UDMincho"; if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); @@ -231,7 +229,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); select(&mut app, 0, 6); choose(&mut app, GlyphForm::Jis83); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Jis83), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); select(&mut app, 3, 6); @@ -244,7 +242,12 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert_eq!(undo_len(&app), n); assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); +} + +/// The characters of `runs` (text and form) drawn in `form`, in order. +fn in_form(runs: &[(String, GlyphForm)], form: GlyphForm) -> String { + runs.iter().filter(|(_, f)| *f == form).map(|(text, _)| text.as_str()).collect() } /// At a caret the glyph form rows act on all the text of the object, so they are checked, and skipped as changing nothing, by @@ -256,14 +259,14 @@ fn glyph_form_items_at_a_caret_follow_all_the_text() { app.session.prefs.show_east_asian_options = true; let node = NodeId(id.as_u64().unwrap_or(0)); let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(node).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.glyph_form).collect::>(), + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), _ => panic!("text"), }; app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), None, "the caret's form is not every character's"); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|f| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), Some(GlyphForm::Jis78)); @@ -1102,3 +1105,110 @@ fn the_grid_lists_the_same_cells_from_the_character_list_read_once() { assert!(list.iter().all(|c| matches!(c, GlyphCell::Glyph(_))), "no character is listed"); assert!(!list.is_empty(), "the glyphs are listed by glyph id"); } + +/// The name a glyph-id cell shows, as the grid names it. +fn glyph_cell_name(face: &vectorcraft_text::FontFace, gid: u32) -> String { + let name = face.glyph_name(gid).unwrap_or_else(|| format!("gid {gid}")); + format!("{name}, glyph {gid}") +} + +/// A right-click on an encoded cell offers Insert Glyph, and choosing it inserts that character in one undo step. +#[test] +fn right_clicking_a_glyph_cell_offers_insert_glyph() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let (mut app, id) = editing("a"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": ALIASED_JOINING_FAMILY})).unwrap(); + select(&mut app, 1, 1); + crate::panels::character::end_typing(&mut app); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(panel.menu_item_enabled("Insert Glyph")); + assert!(!panel.shows("Apply Alternate"), "a character cell offers Insert Glyph"); + panel.click_menu_item("Insert Glyph"); + { + let mut app = panel.app(); + crate::panels::character::end_typing(&mut app); + } + let app = panel.app(); + assert_eq!(plain_of(&app, id), "aB"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(plain_of(&panel.app(), id), "a"); +} + +#[test] +fn insert_glyph_is_disabled_without_a_text_target() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(!panel.menu_item_enabled("Insert Glyph")); +} + +/// In Alternates for Selection a right-click offers Apply Alternate in one undo step. +#[test] +fn right_clicking_an_alternate_cell_offers_apply_alternate() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid, thai_font}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + show_category(&mut app, "Alternates for Selection"); + let list = listed(&mut app, "Alternates for Selection"); + let GlyphCell::Glyph(gid) = list[2] else { panic!("an alternate is a glyph") }; + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let name = glyph_cell_name(&face, gid); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(panel.menu_item_enabled("Apply Alternate")); + assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + // Registering a different family between the menu's opening and the click + // must leave its glyph-ID target valid. + let unrelated = thai_font("VectorCraft Glyph Menu Unrelated Fixture", true).expect("the unrelated test font builds"); + assert!(FontDb::global().add_font(unrelated) > 0); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Alternate")); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(glyph_ids(&app, &json!(id)), [g('B'), g('x'), g('M')]); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&panel.app(), &json!(id)), [g('B'), g('u'), g('M')]); +} + +/// A glyph a double-click would only explain has a disabled menu item, and choosing it changes nothing. +#[test] +fn a_glyph_that_cannot_be_applied_disables_the_menu_item() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let (mut app, id) = editing("\u{0627}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 0, 2); + show_category(&mut app, "stylisticAlternates"); + let gid = u32::from(source_sans_gid('w').expect("a glyph")); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + assert!(cell_info(&mut app, GlyphCell::Glyph(gid)).dimmed, "w is not an alternate of alef"); + let name = glyph_cell_name(&face, gid); + let (undo, status, plain) = (undo_len(&app), app.ui.status.clone(), glyph_ids(&app, &json!(id))); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(!panel.menu_item_enabled("Apply Alternate")); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(glyph_ids(&app, &json!(id)), plain); + assert_eq!(undo_len(&app), undo); + assert_eq!(app.ui.status, status); +} diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d9250ad7ee..7d59220a48 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.style_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect() } @@ -1753,7 +1756,8 @@ mod tests { let app = panel.app(); let names: Vec> = app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); - assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); + let kept = names.iter().filter(|n| n.iter().any(|g| g == "Mine")).count(); + assert_eq!(kept, 2, "both documents keep their style named Mine: {names:?}"); } /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 7650b4d79c..2e0c5b2c57 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -292,6 +292,15 @@ mod tests { use crate::tests::panel_harness::Panel; use craft::ui::contract::Role; + /// English and two translated interface languages, one of them with another script. + fn some_languages() -> [crate::i18n::Lang; 3] { + [ + crate::i18n::Lang::EN, + crate::i18n::Lang::from_code("de").expect("de registered"), + crate::i18n::Lang::from_code("ja").expect("ja registered"), + ] + } + /// A step named after a style lists the template's translation with the style's name in it as /// the document holds it, also when the name looks like a template, like a step with a row of /// its own (`Apply Brush`) or like another template's name; the Normal style's name is @@ -338,7 +347,7 @@ mod tests { /// plain row, else the menu item's row without the ellipsis; a name with no row has none. #[test] fn plain_steps_read_the_menu_row_and_unknown_steps_have_no_name() { - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { let menu_row = crate::i18n::has(lang, "Clean Up…").then(|| crate::i18n::tr(lang, "Clean Up…").trim_end_matches('…').to_string()); let plain_row = crate::i18n::has(lang, "Clean Up").then(|| crate::i18n::tr(lang, "Clean Up").to_string()); assert_eq!(step_name(lang, "Clean Up"), plain_row.or(menu_row), "{}", lang.code()); @@ -347,7 +356,7 @@ mod tests { assert_eq!(step_name(ja, "No Such Step"), None); } - /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// Every built-in effect has one name in each language checked: History (and Edit › Undo and Redo) /// names the step that applied it, and the Appearance panel its row, with the text of its /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its /// menu label with the ellipsis. @@ -366,7 +375,7 @@ mod tests { } assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); let mut differ = Vec::new(); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { crate::i18n::set_current(lang); for (e, h) in &steps { let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; @@ -385,14 +394,14 @@ mod tests { } /// A step another command names like an effect (Object › Transform's `Transform`, the name of - /// Distort & Transform › Transform) keeps its own name in every language. + /// Distort & Transform › Transform) keeps its own name in each language checked. #[test] fn a_step_named_like_an_effect_keeps_its_own_name() { let mut app = app_with_two_rectangles(); app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); } } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 1c7a51edc3..7a1085a152 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1280,11 +1280,7 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { assert_eq!(undo(&panel.app()), steps, "not traced yet"); { let mut app = panel.app(); - let t0 = std::time::Instant::now(); - while !app.trace_runs.running.is_empty() && t0.elapsed() < std::time::Duration::from_secs(30) { - crate::trace_runs::poll(&mut app); - std::thread::sleep(std::time::Duration::from_millis(5)); - } + crate::trace_runs::finish_all(&mut app); assert_eq!(undo(&app), steps + 1, "one undo step"); assert_eq!(param(&app, "strokes"), Some(json!(true))); let st = &app.ui.image_trace_panel.shown; diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index d12f248bb4..d3a874b1e4 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -88,7 +88,7 @@ impl Outcome for CellOutput { } } -/// A row's target circle: a ring, doubled while the row is targeted, with a dot when it has an +/// A row's target circle: a ring, doubled while the row is targeted, with a diamond when it has an /// appearance or transparency of its own ([`target_marks`]). #[derive(Component, Props)] #[component(sample = TargetCircle::sample)] @@ -107,7 +107,13 @@ pub(super) struct TargetCircle { impl TargetCircle { fn new(document: (u64, u64), id: NodeId, targeted: bool, styled: bool) -> Self { - Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None } + let state = match (targeted, styled) { + (true, true) => tl!("Target appearance: targeted, additional appearance or transparency"), + (true, false) => tl!("Target appearance: targeted, basic appearance"), + (false, true) => tl!("Target appearance: not targeted, additional appearance or transparency"), + (false, false) => tl!("Target appearance: not targeted, basic appearance"), + }; + Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None }.tooltip(state).description(state).selected(targeted) } /// A targeted circle with an appearance, for the suite. @@ -186,12 +192,13 @@ impl Component for TargetCircle { let draw = ui.draw(); let (ring, width) = if self.held { (cx.style.accent, StrokeWidth::Medium) } else { (cx.style.ink, StrokeWidth::Thin) }; draw.stroke(&PaintShape::Circle(center, TARGET_RADIUS), width, ring); - let (inner, dot) = target_marks(self.targeted, self.styled); + let (inner, mark) = target_marks(self.targeted, self.styled); if let Some(radius) = inner { draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, cx.style.ink); } - if let Some(radius) = dot { - draw.fill(&PaintShape::Circle(center, radius), cx.style.ink); + if let Some(radius) = mark { + let points = vec![center - vec2(0.0, radius), center + vec2(radius, 0.0), center + vec2(0.0, radius), center - vec2(radius, 0.0)]; + draw.stroke(&PaintShape::Polygon(points), StrokeWidth::Thin, cx.style.ink); } } diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index c7f140123c..ac16b0a92c 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -246,23 +246,20 @@ fn listed_nodes(tree: &DocLayers<'_>, filter: &LayerFilter) -> Vec { pub(super) const TARGET_RADIUS: f32 = 5.0; /// The radius of the inner ring of a targeted item's target circle (the double ring). pub(super) const TARGET_RING: f32 = 2.8; -// PLAN: the sheet keeps `TARGET_STROKE`; the circle's rings take the theme's thin stroke (`StrokeWidth::Thin`), so it is gone. -/// The radius of the dot filling the circle of an item that has an appearance of its own and is -/// not targeted. -pub(super) const TARGET_DOT: f32 = 3.2; -/// The radius of that dot inside a targeted item's inner ring: clear of the ring, so a targeted -/// item with an appearance of its own shows both (#8711). -pub(super) const TARGET_DOT_IN_RING: f32 = 1.5; +/// The radius of the outlined diamond marking an item's own appearance or transparency. +pub(super) const APPEARANCE_MARK: f32 = 2.5; +/// A mitered thin stroke extends a diamond's corner by width / sqrt(2). Radius 1 keeps +/// the diamond clear of the targeted ring's inner edge (#8711). +pub(super) const APPEARANCE_MARK_IN_RING: f32 = 1.0; -/// The marks inside a target circle's outer ring: the inner ring's radius when the item is -/// `targeted`, and the appearance dot's radius when it is `styled` (has an appearance of its own). -/// Each of the four combinations looks different, as the Layers panel's target icons do. +/// The inner target ring's radius and the own-appearance diamond's radius. Each of the four +/// combinations differs, and the diamond inside a targeted ring leaves that ring visible. pub(super) fn target_marks(targeted: bool, styled: bool) -> (Option, Option) { - let dot = if targeted { TARGET_DOT_IN_RING } else { TARGET_DOT }; - (targeted.then_some(TARGET_RING), styled.then_some(dot)) + let mark = if targeted { APPEARANCE_MARK_IN_RING } else { APPEARANCE_MARK }; + (targeted.then_some(TARGET_RING), styled.then_some(mark)) } -/// Whether an object's target circle is filled: its appearance is not basic (a group or layer: +/// Whether an object's target circle shows its appearance mark: its appearance is not basic (a group or layer: /// it has fills, strokes or effects of its own) or its transparency (opacity, blend mode, /// isolation, knockout or an opacity mask) is not the default. pub(super) fn has_styled_target(n: &Node) -> bool { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 7492008a2b..ef54366ba5 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -74,21 +74,15 @@ fn answer(app: &mut VectorcraftApp, ctx: &egui::Context, ok: bool) { crate::dialogs::host::pump(app, ctx); } -/// The target-mark rule: each of the four looks (neither, targeted, an appearance, both) differs, -/// and the dot sits clear of the inner ring, drawn in the theme's thin stroke, when both show. +/// The four target/appearance combinations remain distinct, with the appearance diamond clear of +/// the inner target ring in the theme's thin stroke. #[test] fn target_circle_marks_follow_targeted_and_styled() { - use rows::{TARGET_DOT, TARGET_DOT_IN_RING, TARGET_RING, target_marks}; + use rows::{APPEARANCE_MARK, APPEARANCE_MARK_IN_RING, TARGET_RING, target_marks}; assert_eq!(target_marks(false, false), (None, None)); assert_eq!(target_marks(true, false), (Some(TARGET_RING), None)); - assert_eq!(target_marks(false, true), (None, Some(TARGET_DOT))); - let (ring, dot) = target_marks(true, true); - assert_eq!((ring, dot), (Some(TARGET_RING), Some(TARGET_DOT_IN_RING))); - let thin = std::rc::Rc::new(std::cell::Cell::new(f32::INFINITY)); - let seen = std::rc::Rc::clone(&thin); - let mut fixture = craft::ui::testing::Fixture::new(move |ui| seen.set(craft::ui::runtime::env::Env::of(ui).tokens.stroke.thin)); - fixture.root(crate::app::root_env(&vectorcraft_engine::Prefs::default(), 1.0, None)).frame(vec![]); - assert!(TARGET_DOT_IN_RING + 0.5 < TARGET_RING - thin.get() / 2.0, "the dot covers the ring"); + assert_eq!(target_marks(false, true), (None, Some(APPEARANCE_MARK))); + assert_eq!(target_marks(true, true), (Some(TARGET_RING), Some(APPEARANCE_MARK_IN_RING))); } /// A document with two rectangles on one layer → (app, layer, [bottom, top]). @@ -347,7 +341,7 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() { /// guide kind's ruler, and both glyphs are in the app's icon set. #[test] fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); @@ -361,7 +355,7 @@ fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { }; let (across, down) = (icon_of(false), icon_of(true)); assert_ne!(across, down, "the two kinds of guide rows look alike"); - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for icon in [&across, &down] { assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing"); } @@ -1329,6 +1323,156 @@ fn a_target_circle_drop_after_file_revert_leaves_the_restored_appearance_in_plac assert_eq!(fill(&panel.app(), b), red, "a target circle drag started after the revert still moves the appearance"); } +/// The cardinal four-point outline actually painted by the native cell, independently of its constants. +fn appearance_diamond(shape: &egui::Shape) -> Option<(egui::Pos2, f32, f32)> { + let egui::Shape::Path(path) = shape else { return None }; + if !path.closed || path.fill != egui::Color32::TRANSPARENT || path.points.len() != 4 { + return None; + } + let c = egui::pos2((path.points[0].x + path.points[2].x) / 2.0, (path.points[0].y + path.points[2].y) / 2.0); + let r = path.points[0].distance(c); + if ![2.5, 1.0].iter().any(|expected| (r - expected).abs() < 1e-4) { + return None; + } + let expected = [c - egui::vec2(0.0, r), c + egui::vec2(r, 0.0), c + egui::vec2(0.0, r), c - egui::vec2(r, 0.0)]; + path.points.iter().zip(expected).all(|(a, b)| a.distance(b) < 1e-4).then_some((c, r, path.stroke.width)) +} + +/// The actual native cell's marks at `name`, read from the fixture's paint output: radius, diamond, width. +fn target_marks_painted(panel: &mut crate::tests::panel_harness::Panel, name: &str) -> Vec<(f32, bool, f32)> { + let center = panel.rect(name).center(); + let (shapes, _) = panel.paint_at(1.0); + let ink = shapes + .iter() + .find_map(|shape| match shape { + egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && (circle.radius - 5.0).abs() < 1e-4 => Some(circle.stroke.color), + _ => None, + }) + .expect("the cell's outer target ring"); + for shape in &shapes { + if appearance_diamond(shape).is_some_and(|(at, _, _)| at.distance(center) < 0.01) + && let egui::Shape::Path(path) = shape + { + assert_eq!(path.stroke.color, egui::epaint::ColorMode::Solid(ink), "the native marker keeps the target ring's themed ink"); + assert_eq!(path.stroke.kind, egui::StrokeKind::Middle, "the diamond's stroke is centered on its outline"); + } + } + let mut marks: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::Circle(circle) + if circle.center.distance(center) < 0.01 && circle.radius < 5.0 && circle.fill == egui::Color32::TRANSPARENT => + { + Some((circle.radius, false, circle.stroke.width)) + } + shape => appearance_diamond(shape).filter(|(at, _, _)| at.distance(center) < 0.01).map(|(_, r, width)| (r, true, width)), + }) + .collect(); + marks.sort_by(|a, b| a.0.total_cmp(&b.0)); + marks +} + +/// Retain #8757's historical regression name: the own-appearance diamond leaves the actual inner +/// ring visible, and neither, targeted, styled and both paint four different looks. +#[test] +fn a_targeted_circle_with_an_appearance_shows_both_ring_and_dot() { + use crate::tests::panel_harness::Panel; + let (mut app, _, [a, _]) = two_rects(); + name_row(&mut app, a, "A"); + let mut panel = Panel::new(app, show); + let neither = target_marks_painted(&mut panel, "Target A"); + panel.click("Target A"); + let targeted = target_marks_painted(&mut panel, "Target A"); + panel.app().session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap(); + panel.frame(); + let both = target_marks_painted(&mut panel, "Target A"); + panel.app().session.execute("select.none", &json!({})).unwrap(); + panel.frame(); + let styled = target_marks_painted(&mut panel, "Target A"); + let ring = both.iter().find(|m| (m.0 - 2.8).abs() < 1e-4 && !m.1).expect("the actual inner ring"); + let mark = both.iter().find(|m| m.1).expect("the actual hollow diamond"); + let outer_extent = mark.0 + mark.2 * std::f32::consts::FRAC_1_SQRT_2; + assert!(outer_extent < ring.0 - ring.2 / 2.0 - 0.5, "the diamond {mark:?} covers the ring {ring:?}"); + assert!((mark.0 - 1.0).abs() < 1e-4); + assert_eq!(mark.2, ring.2, "the marker retains the theme's thin stroke"); + let alone = styled.iter().find(|m| m.1).expect("the standalone diamond"); + assert!((alone.0 - 2.5).abs() < 1e-4); + let looks = [&neither, &targeted, &styled, &both]; + for (i, x) in looks.iter().enumerate() { + for y in &looks[i + 1..] { + assert_ne!(x, y, "all four actual cell looks differ"); + } + } +} + +/// Hover and accessibility explain the mark without replacing the contextual row name; the same +/// native cell still targets its art, while selecting other art leaves its own appearance intact. +#[test] +fn appearance_marker_names_its_state_and_keeps_targeting_actions() { + use crate::tests::panel_harness::Panel; + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _language = RestoreLanguage(crate::i18n::current()); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, _, [a, b]) = two_rects(); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap(); + let mut panel = Panel::new(app, show); + let idle = "Target appearance: not targeted, additional appearance or transparency"; + let active = "Target appearance: targeted, additional appearance or transparency"; + assert_eq!(panel.description("Target A").as_deref(), Some(idle)); + assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: not targeted, basic appearance")); + assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(false))); + let before = { + let app = panel.app(); + (app.session.active().unwrap().selection.clone(), undo_len(&app)) + }; + panel.hover("Target A"); + panel.advance(2.0); + panel.frame(); + let (shapes, _) = panel.paint_at(1.0); + assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == idle)), "the native tooltip explains the mark"); + { + let app = panel.app(); + assert_eq!((app.session.active().unwrap().selection.clone(), undo_len(&app)), before, "hover changes no selection or history"); + } + panel.click("Target A"); + assert_eq!(targeted(&panel.app()), (Some(a), vec![a])); + assert_eq!(panel.description("Target A").as_deref(), Some(active)); + assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(true))); + panel.click("Target B"); + assert_eq!(panel.description("Target A").as_deref(), Some(idle)); + assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: targeted, basic appearance")); + assert_eq!(panel.toggled("Target B"), Some(craft::behavior::Mixed::Same(true))); + assert!(target_marks_painted(&mut panel, "Target A").iter().any(|m| m.1), "the appearance stays after targeting other art"); +} + +/// The marker's native cell retains appearance move and Alt-copy admission and payloads. +#[test] +fn dragging_a_target_circle_moves_or_copies_the_appearance() { + use crate::tests::panel_harness::Panel; + let (mut app, layer, [a, b]) = two_rects(); + name_row(&mut app, layer, "Layer"); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap(); + let mut panel = Panel::new(app, show); + let opacity = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().opacity; + panel.drag("Target A", "Target B", egui::Modifiers::ALT); + { + let app = panel.app(); + assert!((opacity(&app, a) - 0.3).abs() < 1e-6 && (opacity(&app, b) - 0.3).abs() < 1e-6); + } + panel.drag("Target B", "Target Layer", egui::Modifiers::NONE); + let app = panel.app(); + assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0); +} + /// The rows find which nodes hold selected art once per revision: frames that change nothing walk no node for the /// selection squares, and a new selection walks the tree once. #[test] diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..02db69a70a 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -15,19 +15,19 @@ //! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state //! (`UiState::library_selection`). +use std::any::Any; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; +use std::rc::Rc; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; use craft::theme::variant::Tone; -use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, Entry, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; -use craft::ui::patterns::presets::{ - PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView, -}; +use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView}; use craft::ui::primitives::{ContentPainterCx, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; @@ -122,7 +122,7 @@ pub(crate) trait LibraryKind { /// The view a panel shows until another is picked. const VIEW: View = View::MediumThumb; /// A library's contents, cheap to clone. - type Lib; + type Lib: Clone + 'static; type Item: Sync; /// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come /// from); `()` for nothing. @@ -135,6 +135,9 @@ pub(crate) trait LibraryKind { fn find(app: &VectorcraftApp, key: &str) -> Found; /// The file library `id` was read from, if any. fn path(app: &VectorcraftApp, id: &str) -> Option; + /// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for + /// `a` while [`get`](Self::get) returns `b`. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool; /// The rows of library `id`; the browser's search filters what it shows (by the shown name and /// [`PresetRow::search_name`]). fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec>; @@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View { /// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click /// selects as it selects an item (production's folder tiles neither opened nor closed). fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> Vec> { + BUILDS.with(|n| n.set(n.get() + 1)); rows.iter() .map(|r| { let label = K::label(id, r.name); @@ -624,22 +628,73 @@ fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> .collect() } +/// A library panel's browser rows, built for one library's contents in one UI language. +struct BuiltRows { + /// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents + /// later stored at the same address. + lib: L, + lang: crate::i18n::Lang, + /// Different for every build, so the browser's memo key changes with the rows. + build: u64, + rows: Rc>>, + /// Each item row's position in [`LibraryKind::rows`], by stored name. + items: Rc>, +} + +thread_local! { + /// Each library panel's [`BuiltRows`], by panel id. + static BUILT_ROWS: RefCell>> = RefCell::new(HashMap::new()); + /// How many times [`browser_rows`] has run, for tests. + static BUILDS: Cell = const { Cell::new(0) }; +} + +/// How many times the panels have built browser rows on this thread. +#[cfg(test)] +pub(crate) fn row_builds() -> u64 { + BUILDS.with(Cell::get) +} + +/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`]. +type Built = (u64, Rc>>, Rc>); + +/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same +/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`. +fn built_rows(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built { + let lang = crate::i18n::current(); + BUILT_ROWS.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::>()) + && b.lang == lang + && K::same(&b.lib, lib) + { + return (b.build, b.rows.clone(), b.items.clone()); + } + let flat = K::rows(lib, id); + let rows = Rc::new(browser_rows::(panel, id, &flat)); + let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect()); + let build = BUILDS.with(Cell::get); + let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) }; + cache.retain(|p, _| is_open(ui, p)); + cache.insert(panel.to_string(), Box::new(built)); + (build, rows, items) + }) +} + /// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with. struct Shown<'a, K: LibraryKind> { + /// [`BuiltRows::build`] of `rows`. + build: u64, rows: &'a [PresetRow], - items: HashMap<&'a str, &'a K::Item>, + flat: &'a [Row<'a, K::Item>], + items: &'a HashMap, thumbs: K::Thumbs, } -/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with. +/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails +/// paint with. impl MemoProps for Shown<'_, K> { fn key(&self, key: &mut MemoKey) { - for row in self.rows { - row.key.key(key); - row.label.key(key); - row.depth.key(key); - (row.kind == PresetKind::Item).key(key); - } + self.build.key(key); self.rows.len().key(key); self.thumbs.key(key); } @@ -658,15 +713,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { }; let panel = panel_id(K::KIND, id); let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find)); + let (build, rows, items) = built_rows::(&app.ui, &panel, id, &lib); let flat = K::rows(&lib, id); - let rows = browser_rows::(&panel, id, &flat); - let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect(); let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| { - if let Some(item) = shown.items.get(info.key.name.as_str()) { + if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) { K::thumb(&shown.thumbs, cx, rect, item); } }); - let source = PresetSource::new(Shown:: { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns); + let source = PresetSource::new(Shown:: { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns); let selection = selected(app, &panel); // The search text and the open groups are the browser's; the view is the panel's setting. let state_id = egui::Id::unique(("library-panel-state", &panel)); @@ -675,7 +729,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let title = library_name(id, &name).to_string(); // The footer stays under the browser, which scrolls in the room left above it. let footer_out = RefCell::new(None); - let any = !selection.items.is_empty() && can_add(app, K::KIND); + let can_add = can_add(app, K::KIND); + let any = !selection.items.is_empty() && can_add; let mut shown = Panel::new(title.clone()) .collection_body() .footer(|ui, _| *footer_out.borrow_mut() = Some(footer_bar::(any).show_footer(ui))) @@ -686,7 +741,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { .select(SelectMode::Multi) .selection(Bind::given(selection.clone())) .empty(tl!("This library is empty.")) - .row_menu(PresetRowMenu::Off) + .row_menu(PresetRowMenu::Host) + .row_items(move |_: &LibraryKey| vec![Entry::new("ui.libraryPanel.add".to_owned(), K::ADD).enabled(can_add)]) + .host_version(u64::from(can_add)) .drags(K::drags()) .show(ui) }); @@ -696,6 +753,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { for event in events { match event { PresetEvent::Selection(change) => chosen.apply(change), + PresetEvent::Menu { target, command, .. } if command == "ui.libraryPanel.add" && can_add => { + let names = + if chosen.items.contains(&target) { chosen.items.iter().map(|key| key.name.clone()).collect() } else { vec![target.name] }; + K::add(app, id, names); + } // A plain click on an item also adds and applies it; folders and modifier clicks only select. PresetEvent::Select { key, mods, .. } if !key.folder && !mods.shift && !mods.cmd => clicked = Some(key.name), _ => {} diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..3220039a1c 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -182,6 +182,42 @@ fn modifier_clicks_select_and_add_to_swatches_adds_the_selection() { assert!(selected_names(&app, "library:swatches:brights").is_empty()); } +#[test] +fn library_item_menu_adds_the_target_or_its_selection_without_applying_paint() { + for view in ["smallList", "smallThumb"] { + for target in ["Clay 1", "Clay 3"] { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": view})).unwrap(); + click(&mut app, &ctx, "Clay 1", Modifiers::COMMAND, 0.0); + click(&mut app, &ctx, "Clay 2", Modifiers::COMMAND, 1.0); + let paint = app.session.paint.fill.clone(); + let undo = undo_len(&app); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let (_, at) = control(&mut app, &ctx, &draw, target); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + draw_frame(&mut app, &ctx, &draw, vec![Event::PointerMoved(at)]); + draw_frame(&mut app, &ctx, &draw, vec![button(true)]); + draw_frame(&mut app, &ctx, &draw, vec![button(false)]); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let (_, row) = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some("Add to Swatches")).unwrap(); + let bounds = row.bounds().unwrap(); + assert_eq!(undo_len(&app), undo, "opening the item menu must not edit the drawing"); + let expected = if target == "Clay 1" { vec!["Clay 1", "Clay 2"] } else { vec!["Clay 3"] }; + assert_eq!(selected_names(&app, &panel), expected); + click_at(&mut app, &ctx, &draw, Pos2::new((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5)); + for name in ["Clay 1", "Clay 2", "Clay 3"] { + assert_eq!(app.session.doc().unwrap().doc.swatch(name).is_some(), expected.contains(&name), "{view}: {target}: {name}"); + } + assert_eq!(app.session.paint.fill, paint); + } + } +} + #[test] fn adding_selected_library_items_requires_an_open_drawing() { let mut app = app(); @@ -786,3 +822,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() { assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name"); crate::i18n::set_current(crate::i18n::Lang::EN); } + +/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again +/// when the UI language changes the names it lists. +#[test] +fn library_panel_builds_its_rows_once_per_library_and_language() { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap(); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let before = row_builds(); + for _ in 0..4 { + draw_frame(&mut app, &ctx, &draw, vec![]); + } + assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once"); + let painted = crate::tests_labels::shapes_text(&out); + assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}"); +} diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 8715d02401..43174d8f9e 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -855,7 +855,39 @@ mod tests { let mut app = selected_text(); let Some((st, _)) = text_style(&app) else { panic!("no text style") }; let sets = set_entries(&app, &st); - // Builds without the bundled fonts have no face that offers sets. + // With the bundled fonts, the text's face offers sets. Without them, an installed face may. + assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); + // The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from + // the face itself, so the test returns early only when the face offers none. + let db = FontDb::global(); + let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0); + let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() }; + let expected: Vec = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect(); + let listed: Vec = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect(); + assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face"); + let rows = menu_rows(&app); + if expected.is_empty() { + assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets"); + } else { + let submenu = rows.iter().find_map(|row| match row { + PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub), + _ => None, + }); + let actual: Vec<&str> = submenu + .expect("the menu has a Stylistic Sets submenu") + .iter() + .filter_map(|row| match row { + PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")), + _ => None, + }) + .collect(); + assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order"); + } + for tag in &expected { + let r = toggle_ref(tag); + assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); + } + // Only an installed face without bundled fonts can offer no set; the rows above are checked. let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); @@ -941,7 +973,9 @@ mod tests { assert_eq!(state_of(&app, &toggle_ref(tag)), Some(toggled(label, false)), "{label}"); run(&mut app, TOGGLE, &json!({"tag": tag})).unwrap().unwrap(); let runs = run_features(&mut app, &id, 8); - assert!(runs.iter().all(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); + let tagged: String = + runs.iter().filter(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))).map(|(t, _)| t.as_str()).collect(); + assert_eq!(tagged, "かなAB", "{label}: {runs:?}"); } } @@ -992,6 +1026,11 @@ mod tests { } } + /// The characters of `runs` ([`metrics_runs`]) whose Proportional Metrics and features `keep` accepts. + fn text_where(runs: &[(String, bool, Vec)], keep: impl Fn(bool, &[String]) -> bool) -> String { + runs.iter().filter(|(_, on, f)| keep(*on, f)).map(|(t, _, _)| t.as_str()).collect() + } + /// Where the panel menu's top-level rows list the command `r`. fn row_index(rows: &[PanelRow], r: &CommandRef) -> Option { rows.iter().position(|row| matches!(row, PanelRow::Command(c) if c == r)) @@ -1037,13 +1076,14 @@ mod tests { assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": true})))); assert_eq!(undo_steps(&app), undo + 1); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); - assert_eq!(runs.iter().map(|(t, _, f)| (t.as_str(), f.clone())).collect::>(), [("か", vec!["smcp".to_string()]), ("なAB", vec![])]); + assert_eq!(runs, [("か".to_string(), true, vec!["smcp".to_string()]), ("なAB".to_string(), true, vec![])]); assert_eq!(state_of(&app, &metrics), Some(toggled("Proportional Metrics", true))); assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": false})))); assert_eq!(undo_steps(&app), undo + 2); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, f)| !*on && (f.is_empty() || *f == ["smcp"])), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "", "{runs:?}"); + assert_eq!(text_where(&runs, |_, f| f == ["smcp"]), "か", "each run keeps its features: {runs:?}"); + assert_eq!(text_where(&runs, |_, f| f.is_empty()), "なAB", "{runs:?}"); } /// With the Selection tool, Proportional Metrics turns on for the whole selected object. At a @@ -1058,7 +1098,7 @@ mod tests { let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); - assert!(metrics_runs(&app, &id).iter().all(|(_, on, _)| *on), "{:?}", metrics_runs(&app, &id)); + assert_eq!(text_where(&metrics_runs(&app, &id), |on, _| on), "かなAB"); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.prefs.show_east_asian_options = true; @@ -1073,7 +1113,7 @@ mod tests { assert_eq!(state_of(&app, &CommandRef::new(METRICS)), Some(toggled("Proportional Metrics", false))); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "かなAB", "{runs:?}"); } /// With Real-time Drawing off, Proportional Metrics and H or V Style decide from the text with diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 75310b3f35..8d2ea06ab8 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -282,7 +282,7 @@ fn kinsoku_set_shows_a_custom_set_by_name() { } /// The Mojikumi Set menu lists None, the four other predefined sets and Line-end Punctuation Half -/// Width, each under its own label in every interface language. Each entry sets the selected +/// Width, each under its own label in English and in Japanese. Each entry sets the selected /// paragraphs' set in one undo step and is shown as the current set; paragraphs with different /// sets show a blank menu, and Reset Panel gives them Line-end Punctuation Half Width. #[test] @@ -290,7 +290,7 @@ fn mojikumi_menu_offers_and_sets_every_predefined_set() { let keys: Vec<&str> = mojikumi_sets().iter().map(|s| s.2).collect(); assert_eq!(keys, ["none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku", "lineEndHalf"]); use crate::i18n::LangExt as _; - for lang in crate::i18n::Lang::all() { + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("ja").expect("ja registered")] { crate::i18n::set_current(lang); let labels: std::collections::BTreeSet<&str> = mojikumi_sets().iter().map(|s| s.0).collect(); crate::i18n::set_current(crate::i18n::Lang::EN); @@ -680,10 +680,8 @@ fn the_numbered_list_button_and_its_presets_set_the_list_and_reset_panel_clears_ assert_eq!(lists(&app), (numbered(NumberStyle::Arabic), None), "the caret's paragraph"); assert_eq!(numbers_shown(&app), Some(Some(NumberStyle::Arabic)), "the button shows pressed"); assert_eq!(number_sample(NumberStyle::UpperRoman, 3), "I, II, III"); - for style in NumberStyle::ALL { - set_number_style(&mut app, Some(style)); - assert_eq!(lists(&app), (numbered(style), None), "{}", number_sample(style, 3)); - } + set_number_style(&mut app, Some(NumberStyle::UpperRoman)); + assert_eq!(lists(&app), (numbered(NumberStyle::UpperRoman), None), "a preset picks its style"); set_number_style(&mut app, None); assert_eq!(lists(&app), (None, None)); app.session.set_tool_option("selectAll", &json!(true)); diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 93e93681f2..86460a42f7 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -267,6 +267,30 @@ mod tests { Panel::new(app, show) } + #[test] + fn scrolling_a_short_docked_form_reaches_its_last_action() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots"})).unwrap(); + let mut panel = Panel::new(app, |app, ui| crate::dock::panel_body(app, ui, "patternOptions")); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + panel.room(viewport.size()); + panel.frame(); + panel.frame(); + let before = panel.rect("Done"); + assert!(before.center().y > viewport.bottom(), "Done starts at {before:?} in {viewport:?}"); + for _ in 0..20 { + panel.scroll_at(egui::pos2(30.0, 30.0), -120.0); + panel.advance(0.2); + panel.frame(); + } + let after = panel.rect("Done"); + assert!(viewport.contains(after.center()), "Done moved from {before:?} to {after:?} in {viewport:?}"); + panel.click("Done"); + assert!(editing(&panel.app()).is_none()); + } + /// Shift+Enter in the Name field renames the pattern and keeps the field active; Enter then /// renames it again and ends the editing. #[test] @@ -309,4 +333,44 @@ mod tests { assert_eq!(panel.value("Name").as_deref(), Some("Dots")); assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some()); } + + /// The tile's width and height of the pattern "Dots". + fn tile_size(panel: &Panel) -> (f64, f64) { + let app = panel.app(); + let tile = &app.session.active().unwrap().doc.pattern("Dots").unwrap().tile; + (tile.width(), tile.height()) + } + + /// With the Width field focused, a wheel notch steps it only while the pointer is over it: over another control, + /// or over the unfocused Height field, the wheel scrolls the panel and the tile keeps its size. + #[test] + fn the_wheel_steps_the_focused_number_field_only_under_the_pointer() { + use craft::ui::contract::Role; + let mut panel = editing_panel(); + panel.room(egui::vec2(220.0, 320.0)); + panel.frame(); + assert_eq!(tile_size(&panel), (10.0, 10.0)); + panel.click_role("Width", Role::SPIN_BUTTON); + assert!(panel.focused("Width"), "the click focuses Width"); + + // One notch at `at`, then the frame after the wheel gesture's gap, which ends the gesture. + let notch = |panel: &mut Panel, at: egui::Pos2| { + panel.scroll_at(at, -30.0); + panel.advance(1.0); + panel.frame(); + }; + + let check = panel.rect("Size Tile to Art").center(); + notch(&mut panel, check); + assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over Size Tile to Art leaves the focused Width alone"); + assert!(panel.focused("Width"), "Width keeps the focus"); + + let height = panel.rect_role("Height", Role::SPIN_BUTTON).center(); + notch(&mut panel, height); + assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over the unfocused Height steps neither field"); + + let width = panel.rect_role("Width", Role::SPIN_BUTTON).center(); + notch(&mut panel, width); + assert_eq!(tile_size(&panel), (9.0, 10.0), "a notch over the focused Width steps it"); + } } diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index 9ee83019d9..923d07b793 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -13,6 +13,7 @@ use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, S use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::list::{Finding, FindingsList, FindingsWords, ListRow, Severity}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::pickers::Select; use craft::ui::runtime::frame::clock; @@ -30,6 +31,8 @@ const RECHECK: f64 = 2.0; pub(crate) struct PreflightPanel { pub(crate) options: Options, pub(crate) cache: Cache, + /// The document and finding for the open row menu. Report positions can change on recheck. + menu: Option<(u64, Value)>, } /// What the user chose to check. @@ -213,6 +216,15 @@ fn heading_row<'r>(check: &Value, pending: &'r Pending) -> ListRow<'r> { row } +fn link_action(finding: &Value) -> Option<(&str, &'static str, u64)> { + let id = finding["sourceId"].as_u64()?; + match finding["code"].as_str()? { + "missingLink" => Some((tl!("Relink…"), "ui.relinkDialog", id)), + "modifiedLink" => Some((tl!("Update Link"), "links.update", id)), + _ => None, + } +} + /// The row of one finding, with the button that repairs a link under it. fn finding_row<'r>(key: u64, finding: &Value, words: &FindingsWords, pending: &'r Pending) -> ListRow<'r> { let code = finding["code"].as_str().unwrap_or_default(); @@ -221,14 +233,9 @@ fn finding_row<'r>(key: u64, finding: &Value, words: &FindingsWords, pending: &' let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::>(); detail = format!("{detail}; {}", effective_ppi_line(&values)); } - let row = Finding::new(key, Severity::Warning, finding["name"].as_str().unwrap_or_default()).detail(detail).row(words); - let action = match code { - "missingLink" => Some((tl!("Relink…"), "ui.relinkDialog")), - "modifiedLink" => Some((tl!("Update Link"), "links.update")), - _ => None, - }; - match (action, finding["sourceId"].as_u64()) { - (Some((label, command)), Some(id)) => row.below(Button::new(label.to_owned()), move |out| { + let row = Finding::new(key, Severity::Warning, finding["name"].as_str().unwrap_or_default()).detail(detail).row(words).row_menu(); + match link_action(finding) { + Some((label, command, id)) => row.below(Button::new(label.to_owned()), move |out| { if out.clicks == 1 { pending.borrow_mut().push((command, json!({ "ids": [id] }))); } @@ -280,43 +287,74 @@ fn options(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - if app.session.active().is_none() { + let Some(document) = app.session.active().map(|st| st.uid) else { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Neutral, tl!("Open a document to check it before delivery.").to_owned()) .title(tl!("Production Preflight").to_owned()) .layout(NoticeLayout::Centred) .show(ui); return; - } + }; let force = options(app, ui); Divider::horizontal().show(ui); if app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy() { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Neutral, tl!("Preflight updates when the edit finishes.").to_owned()).layout(NoticeLayout::Centred).show(ui); return; } let cache = cached(app, ui, force); if let Some(error) = cache.error { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Bad, crate::i18n::msg(&error)).title(tl!("Preflight could not complete").to_owned()).layout(NoticeLayout::Centred).show(ui); return; } - results(app, ui, &cache.report); + results(app, ui, document, &cache.report); } -fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { +fn results(app: &mut VectorcraftApp, ui: &mut Ui, document: u64, report: &Value) { let rows = PreflightRows::new(report); let pending = Pending::default(); - let out = FindingsList::new(tl!("Findings")).show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { + let list = FindingsList::new(tl!("Findings")).id(ui.scope_id().with(("preflight-findings", document))); + let out = list.show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { Some(Entry_::Heading(c)) => heading_row(&rows.checks[*c], &pending), Some(Entry_::Finding(f)) => finding_row(*key, &rows.findings[*f], &icx.words::(), &pending), None => ListRow::new(String::new()), }); let mut located = None; + let finding_at = |key: u64| match rows.entries.get(rows.index_of(&key)?)? { + Entry_::Finding(f) => rows.findings.get(*f), + Entry_::Heading(_) => None, + }; + let menu = &mut app.ui.preflight_panel.menu; for event in out.events { - if let CollectionEvent::Activate(key) = event - && let Some(Entry_::Finding(f)) = usize::try_from(key).ok().and_then(|at| rows.entries.get(at)) - { - located = rows.findings.get(*f); + match event { + CollectionEvent::ContextMenu(request) => *menu = finding_at(request.key).map(|f| (document, f.clone())), + CollectionEvent::Activate(key) => located = finding_at(key), + _ => {} } } + // Resolve the captured finding in the current report even if another row now occupies its old slot. + let target = menu.as_ref().filter(|(uid, _)| *uid == document).and_then(|(_, saved)| rows.findings.iter().find(|f| *f == saved)); + if let Some(finding) = target { + let shown = Menu::context(tl!("Findings"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Select and Zoom")).show(ui).ran { + located = Some(finding); + } + if finding["kind"] == "fonts" && MenuItem::new(tl!("Find Font…")).show(ui).ran { + pending.borrow_mut().push(("type.findFont", json!({}))); + } + if let Some((label, command, id)) = link_action(finding) + && MenuItem::new(label.to_owned()).show(ui).ran + { + pending.borrow_mut().push((command, json!({ "ids": [id] }))); + } + }); + if shown.output.closed.is_some() || located.is_some() || !pending.borrow().is_empty() { + *menu = None; + } + } else { + *menu = None; + } if let Some(finding) = located { locate(app, finding); } diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs index 18f9ad57c4..0220b447c2 100644 --- a/crates/ui-egui/src/panels/preflight/tests.rs +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -131,6 +131,77 @@ fn clicking_a_preflight_finding_selects_and_zooms_to_its_artwork() { assert!(app.view().unwrap().zoom > 1.0); } +#[test] +fn a_finding_menu_can_be_opened_dismissed_and_run_from_the_keyboard() { + use egui::{Key, Modifiers}; + + let (mut app, id) = app(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + big_canvas(&mut app); + let overflow = row(&mut app, "overflow"); + let mut panel = Panel::new(app, show); + panel.focus(&overflow); + assert!(panel.focused(&overflow)); + + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Select and Zoom")); + assert!(panel.app().session.active().unwrap().selection.objects.is_empty()); + + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Select and Zoom")); + assert!(panel.focused(&overflow)); + + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + panel.key(Key::Enter, Modifiers::NONE); + app_frame(&mut panel.app()); + let app = panel.app(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id.as_u64().unwrap())]); + assert!(app.view().unwrap().fitted); +} + +#[test] +fn a_finding_menu_stays_on_its_original_finding_after_recheck() { + let (mut app, first) = app(); + let second = app.run("text.create", json!({ "x": 120, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight UI Missing 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + app.run("object.setProps", json!({ "ids": [second], "name": "Back page" })).unwrap(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + let overflow = |name: &str| format!("{name}, {}, Warning", reason("overflow")); + let mut panel = Panel::new(app, show); + panel.secondary_click(&overflow("Back page")); + panel.frame(); + assert!(panel.shows("Select and Zoom")); + + panel.app().run("text.areaOptions", json!({ "ids": [first], "height": 150 })).unwrap(); + panel.frame(); + assert!(!panel.shows(&overflow("Delivery headline"))); + panel.click_menu_item("Select and Zoom"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(second.as_u64().unwrap())]); +} + +#[test] +fn switching_documents_dismisses_the_finding_menu() { + let (mut app, _) = app(); + let font = row(&mut app, "missingFont"); + let mut panel = Panel::new(app, show); + panel.secondary_click(&font); + panel.frame(); + assert!(panel.shows_role("Find Font…", craft::ui::contract::Role::MENU_ITEM)); + + panel.app().run("file.new", json!({ "width": 500, "height": 400 })).unwrap(); + panel.frame(); + assert!(!panel.shows("Select and Zoom")); + panel.app().run("document.activate", json!({ "index": 0 })).unwrap(); + panel.frame(); + assert!(panel.shows(&font)); + assert!(!panel.shows("Select and Zoom")); +} + #[test] fn clicking_a_preflight_finding_on_a_locked_artboard_reports_the_problem() { let (mut app, id) = app(); @@ -218,8 +289,15 @@ fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() { panel.frame(); assert!(panel.shows(&missing)); assert_eq!(rev, panel.app().session.active().unwrap().revision); + panel.secondary_click(&missing); + panel.frame(); + assert!(panel.shows_role("Relink…", craft::ui::contract::Role::MENU_ITEM)); std::fs::write(&path, &bytes).unwrap(); - panel.click("Recheck"); + panel.advance(2.0); + panel.frame(); + assert!(!panel.shows("Select and Zoom"), "the timer dismissed the menu for a resolved finding"); assert!(!panel.shows(&missing)); std::fs::remove_file(&path).unwrap(); + panel.click("Recheck"); + assert!(panel.shows(&missing), "Recheck notices a newly missing file before the timer"); } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 7e3caa1a43..06d19cd822 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,13 +1,13 @@ //! The Properties panel: sections that change with the selection. -use craft::behavior::{ColumnWidth, IconId}; +use craft::behavior::{ColumnWidth, IconId, Proposal}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{LabelScheme, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{BodyCx, LabelScheme, Pad, Props as _, Show as _, ShowContainer as _}; use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::panels::Inspector; use craft::ui::runtime::commands::CommandRef; -use craft::ui::sections::HeaderStrength; +use craft::ui::sections::{HeaderStrength, Panel}; use egui::Ui; use serde_json::json; use vectorcraft_doc::{LiveShape, Node, NodeKind}; @@ -27,6 +27,12 @@ pub struct PropertiesUi { pub edited_profiled: Option<(ProfiledKey, bool)>, /// The Quick Actions last listed, with the [`quick_actions_key`] they were listed at. quick_actions: Option<(u64, Vec)>, + /// The [`content_key`] the sections were last shown for. + content: Option, + /// The document (uid, revision) the sections were last shown for. + revision: Option<(u64, u64)>, + /// An edit made during a drag whose sections are not measured yet. + measure_pending: bool, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -63,7 +69,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Ruler guides selected on their own (a click on one): their position. let guides = super::transform::selected_guides(app); let header = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); - inspector.target(key).header(header).show(ui, |ui, _| { + let content = content_key(app); + let revision = app.session.active().map(|st| (st.uid, st.revision)); + let content_changed = app.ui.properties_panel.content.replace(content) != Some(content); + let edited = std::mem::replace(&mut app.ui.properties_panel.revision, revision) != revision; + // A drag on the canvas, or a scrubbed field, moves the revision on every pointer move without changing which + // sections show: the sections are measured again for an edit once the drag ends, not on each move. The edit stays + // pending until then, also when the release itself does not move the revision. + let dragging = app.session.active().is_some_and(|st| st.interaction.is_some() || st.undo_group.is_some()); + let pending = app.ui.properties_panel.measure_pending || edited; + let changed = content_changed || (pending && !dragging); + app.ui.properties_panel.measure_pending = pending && !changed; + let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| { // The reference panel's labels end in a colon beside fields that keep their own width. Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| { if editing_artboards { @@ -77,7 +94,35 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { body(app, ui, first.as_deref(), n_sel, anchors); } }); - }); + }; + // The panel `Inspector::show` makes, shown here so that new sections are measured before they are placed and the + // frame is not discarded and drawn again. + let mut panel = Panel::new(header).titled().strength(HeaderStrength::Quiet).labels(LabelScheme::Inspector).pad(Pad::None); + panel = panel.id_salt(egui::IdSalt::new(key)); + if changed { + #[cfg(test)] + SECTION_MEASURES.with(|n| n.set(n.get() + 1)); + let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections); + } + panel.show(ui, sections); +} + +/// What the sections show besides the document's revision: the document, the selection, the tool and isolation mode. +fn content_key(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + app.session.tool_id().hash(&mut h); + if let Some(st) = app.session.active() { + let selection = &st.selection; + (st.uid, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); + for (id, anchors) in &selection.anchors { + (id, anchors.len()).hash(&mut h); + } + for (id, segments) in &selection.segments { + (id, segments.len()).hash(&mut h); + } + } + h.finish() } /// The document's uid: production's field ids do not change with the selection, so neither does the key and the @@ -193,6 +238,8 @@ fn quick_actions_key(app: &VectorcraftApp) -> u64 { thread_local! { /// How many times this thread has listed the Quick Actions. pub(crate) static QUICK_ACTION_LISTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times this thread has measured the panel's sections before showing them. + pub(crate) static SECTION_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`quick_actions`], listed again only when [`quick_actions_key`] changed. @@ -291,8 +338,9 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { }) } -/// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor -/// quick action; memoised per document revision. +/// Whether the selection uses more than one colour (`recolor.colors` lists more than one, +/// [`vectorcraft_engine::Session::several_colors_used`]), which offers the Recolor quick action; +/// memoised per document revision. pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool { let Some(st) = app.session.active() else { return false }; let key = (st.uid, st.revision); @@ -301,19 +349,19 @@ pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool { { return multi; } - let r = app.session.execute("recolor.colors", &json!({})).unwrap_or_default(); - let multi = r["colors"].as_array().is_some_and(|c| c.len() > 1); + let multi = app.session.several_colors_used(); app.canvas.multi_color = Some((key, multi)); multi } /// The panel's heading: what the sections are for (the artboards with the Artboard tool, the -/// selected ruler guides, the document with nothing selected), else the selection's kind. +/// selected ruler guides), No Selection with nothing selected (the Document section follows it), else the +/// selection's kind. fn heading(first: Option<&vectorcraft_doc::Node>, n_sel: usize, editing_artboards: bool, guides: bool) -> String { match (first, n_sel) { _ if editing_artboards => tl!("Artboard").to_string(), (None, _) if guides => tl!("Guides").to_string(), - (None, _) => tl!("Document").to_string(), + (None, _) => tl!("No Selection").to_string(), (_, n) if n > 1 => crate::i18n::tn(n as u64, "{n} Object", "{n} Objects"), (Some(n), _) if crate::panels::image_trace::is_trace(n) => tl!("Image Tracing").to_string(), (Some(n), _) => tl!(n.kind_label()).to_string(), diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index e8c14ba4dd..d702cbf899 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -1,10 +1,10 @@ //! The Properties panel's Document sections, shown with nothing selected. -use craft::behavior::IconId; +use craft::behavior::{EditEvent, IconId}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, ToggleButton}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft::ui::contract::{Bind, Entry, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _, Sizing}; use craft::ui::form::Field; use craft::ui::layout_components::{Grid, Row}; use craft::ui::pickers::Select; @@ -17,84 +17,246 @@ use vectorcraft_doc::Unit; use super::artboard_sections::rearrange_button; use super::object_sections::HALVES; use crate::VectorcraftApp; +use crate::edits::EditPath; use crate::panels::transform; /// The panel with nothing selected: the document's units, Document Setup and artboards, the /// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard /// increment and Scale Strokes & Effects, and Quick Actions. +/// +/// Every section but Appearance shows in a `MemoView` keyed on what it reads, header and body together, +/// so a frame that changes none of it replays the whole section. What a section picks comes back +/// through an `Outbox` and runs after it. pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { + let lang = crate::i18n::current(); let units = app.session.general_unit(); + let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX); let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len()); - super::section(tl!("Document")).show(ui, |ui, _| { - Field::new(tl!("Units")).show(ui, |ui, _| { - let entries: Vec> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect(); - let out = Select::new(tl!("Units"), Bind::given(units), &entries).show(ui); - if let Some(u) = out.events.committed() { - app.run("document.setUnits", json!({ "units": u.label() })).ok(); - } - }); - Grid::new(&HALVES).show(ui, |ui, _| { - Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui); - Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" }))) - .label(tl!("Edit Artboards")) - .sizing(Sizing::FillWidth) - .show(ui); - if artboards > 1 { - rearrange_button(ui, artboards); - } - }); - }); + let mut picked_units = Vec::new(); + let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; + memoized("properties-document", document, document_section, ui); + if let Some(u) = picked_units.pop() { + app.run("document.setUnits", json!({ "units": u.label() })).ok(); + } super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui)); - super::section(tl!("Rulers & Grids")).show(ui, |ui, _| { - Row::new().show(ui, |ui, _| { - // The checked and enabled states and the tooltips come from the commands (Trim View turns the grid off). - for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] { - ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui); - } - }); - }); - super::section(tl!("Guides")).show(ui, |ui, _| { - Row::new().show(ui, |ui, _| { - for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] { - ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui); - } - }); - }); - super::section(tl!("Snap Options")).show(ui, |ui, _| { - let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid); - for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), point), ("view.snapToGrid", tl!("Snap to Grid"), grid)] { - if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() { - app.run(command, json!({})).ok(); + memoized("properties-rulers", Language { lang }, rulers_section, ui); + memoized("properties-guides", Language { lang }, guides_section, ui); + let mut snaps = Vec::new(); + let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid); + let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; + memoized("properties-snap", snap, snap_section, ui); + for command in snaps { + app.run(command, json!({})).ok(); + } + let mut prefs = Vec::new(); + // Read again after the Units commit above, so the key and `lengths` come from the same General unit. + let general = app.session.general_unit(); + let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX); + let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes); + let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app)); + let picked = Outbox::new(&mut prefs); + let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; + memoized("properties-preferences", preferences, preferences_section, ui); + for pick in prefs { + match pick { + PreferencePick::Increment(event) => { + crate::edits::apply_event(app, &event, &EditPath::Scope, &mut |app, v: &Option, _| { + if let Some(value) = *v { + app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok(); + } + }); } + PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on), + } + } + memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); +} + +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. A section scrolled out of view still runs or replays, so +/// its controls keep their focus stops and accessibility nodes. Tests can show it directly instead, to compare where +/// the memoized sections land with where direct ones do. +fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { + #[cfg(test)] + if tests::shown_directly() { + let mut props = props; + section(&mut props, ui); + return; + } + let _ = MemoView::new(id, props, section).shown_out_of_view().show(ui); +} + +/// The Document section: its header and [`document_body`]. +fn document_section(p: &mut DocumentProps<'_>, ui: &mut Ui) { + super::section(tl!("Document")).show(ui, |ui, _| document_body(p, ui)); +} + +/// The Rulers & Grids section: its header and [`rulers_body`]. +fn rulers_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Rulers & Grids")).show(ui, |ui, _| rulers_body(p, ui)); +} + +/// The Guides section: its header and [`guides_body`]. +fn guides_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Guides")).show(ui, |ui, _| guides_body(p, ui)); +} + +/// The Snap Options section: its header and [`snap_body`]. +fn snap_section(p: &mut SnapProps<'_>, ui: &mut Ui) { + super::section(tl!("Snap Options")).show(ui, |ui, _| snap_body(p, ui)); +} + +/// The Preferences section: its header and [`preferences_body`]. +fn preferences_section(p: &mut PreferencesProps<'_>, ui: &mut Ui) { + super::section(tl!("Preferences")).show(ui, |ui, _| preferences_body(p, ui)); +} + +/// The Quick Actions section: its header and [`quick_actions_body`]. +fn quick_actions_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Quick Actions")).show(ui, |ui, _| quick_actions_body(p, ui)); +} + +/// What a section that reads only command states reads besides them: the interface language of its labels. +#[derive(MemoProps)] +struct Language { + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, +} + +/// What the Document section reads: the document's units and how many artboards it has. +#[derive(MemoProps)] +struct DocumentProps<'a> { + /// The index of `units` in [`Unit::ALL`]. + unit: usize, + #[memo_props(covered_by = "unit", reason = "the unit's index in Unit::ALL")] + units: Unit, + /// How many artboards the document has (Rearrange All shows for more than one). + artboards: usize, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// The units chosen in the Units menu. + picked: Outbox<'a, Unit>, +} + +/// The Document section's body: Units, Document Setup, Edit Artboards and Rearrange All. +fn document_body(p: &mut DocumentProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + Field::new(tl!("Units")).show(ui, |ui, _| { + let entries: Vec> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect(); + let out = Select::new(tl!("Units"), Bind::given(p.units), &entries).show(ui); + if let Some(u) = out.events.committed() { + p.picked.send(*u); } }); - super::section(tl!("Preferences")).show(ui, |ui, _| { - Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| { - // PLAN: assumed `canvas::rulers::general_lengths(app) -> LengthUnits` (cv.B5b) - let lengths: LengthUnits = crate::canvas::rulers::general_lengths(app); - // The engine's own range for the preference (`prefscmds.rs`): a larger value is an error. - let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(app.session.prefs.keyboard_increment)), lengths) - .range(0.001..=1296.0) - .show(ui); - crate::edits::apply_edits(app, &out.edit, crate::edits::EditPath::Scope, |app, v: &Option, _| { - if let Some(value) = *v { - app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok(); - } - }); - }); - let scale = app.session.prefs.scale_strokes; - let out = Checkbox::new(Bind::given(scale)).label(tl!("Scale Strokes & Effects")).show(ui); - if let Some(on) = out.value().copied() { - transform::set_pref(app, "scaleStrokes", on); + Grid::new(&HALVES).show(ui, |ui, _| { + Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui); + Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" }))) + .label(tl!("Edit Artboards")) + .sizing(Sizing::FillWidth) + .show(ui); + if p.artboards > 1 { + rearrange_button(ui, p.artboards); } }); - super::section(tl!("Quick Actions")).show(ui, |ui, _| { - Grid::new(&HALVES).show(ui, |ui, _| { - // The reference panel's buttons name the dialog without the menu's ellipsis. - for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] { - Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui); - } - }); +} + +/// The Rulers & Grids section's body. The checked and enabled states and the tooltips come from the commands (Trim +/// View turns the grid off). +fn rulers_body(_: &mut Language, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + Row::new().show(ui, |ui, _| { + for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] { + ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui); + } + }); +} + +/// The Guides section's body: Show Guides and Smart Guides, from their commands. +fn guides_body(_: &mut Language, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + Row::new().show(ui, |ui, _| { + for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] { + ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui); + } + }); +} + +/// What the Snap Options section reads: whether Snap to Point and Snap to Grid are on. +#[derive(MemoProps)] +struct SnapProps<'a> { + point: bool, + grid: bool, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// The command of each checkbox clicked. + picked: Outbox<'a, &'static str>, +} + +/// The Snap Options section's body: Snap to Point and Snap to Grid. +fn snap_body(p: &mut SnapProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), p.point), ("view.snapToGrid", tl!("Snap to Grid"), p.grid)] { + if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() { + p.picked.send(command); + } + } +} + +/// What the Preferences section reads: the keyboard increment in the General unit, and Scale Strokes & Effects. +#[derive(MemoProps)] +struct PreferencesProps<'a> { + /// The keyboard increment, in points. + increment: f64, + /// The index of the General unit in [`Unit::ALL`]. + unit: usize, + /// Numbers without units are points (Preferences › Units). + bare_points: bool, + #[memo_props(covered_by = "unit", reason = "made from the General unit and bare_points alone (canvas::rulers::lengths)")] + lengths: LengthUnits, + /// Scale Strokes & Effects is on. + scale: bool, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// The keyboard increment's edits and the Scale Strokes & Effects choice. + picked: Outbox<'a, PreferencePick>, +} + +/// What the Preferences section reports: an edit of the keyboard increment, or Scale Strokes & Effects turned on or +/// off. +enum PreferencePick { + Increment(EditEvent>), + ScaleStrokes(bool), +} + +/// The Preferences section's body: Keyboard Increment and Scale Strokes & Effects. +fn preferences_body(p: &mut PreferencesProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| { + // The engine's own range for the preference (`prefscmds.rs`): a larger value is an error. + let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(p.increment)), p.lengths).range(0.001..=1296.0).show(ui); + for event in out.edit.events.iter() { + p.picked.send(PreferencePick::Increment(event.clone())); + } + }); + let out = Checkbox::new(Bind::given(p.scale)).label(tl!("Scale Strokes & Effects")).show(ui); + if let Some(on) = out.value().copied() { + p.picked.send(PreferencePick::ScaleStrokes(on)); + } +} + +/// The Quick Actions section's body: Document Setup and Preferences. The reference panel's buttons name the dialog +/// without the menu's ellipsis. +fn quick_actions_body(_: &mut Language, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + Grid::new(&HALVES).show(ui, |ui, _| { + for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] { + Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui); + } }); } @@ -104,6 +266,76 @@ mod tests { use crate::tests::panel_harness::Panel; use craft::ui::contract::Role; + thread_local! { + /// How many times this thread ran a memoized Document section. + static SECTION_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_run() { + SECTION_RUNS.with(|n| n.set(n.get() + 1)); + } + + fn runs() -> u64 { + SECTION_RUNS.with(std::cell::Cell::get) + } + + thread_local! { + /// This thread shows the memoized sections directly, outside their `MemoView`s. + static DIRECT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(std::cell::Cell::get) + } + + /// The runs of text the whole Properties panel paints with nothing selected, after idle frames that replay the + /// memoized sections, with the sections shown in their `MemoView`s or, with `direct`, directly. + fn panel_texts(direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.frame(); + let before = runs(); + panel.frame(); + panel.frame(); + if !direct { + assert_eq!(runs(), before, "the last frames replay the memoized sections"); + } + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// Whole sections shown in `MemoView`s, header and body, land where the same sections shown directly do under the + /// app's `SectionRhythm::Spaced` and `QuietHeader::Heads`: the Document section under the panel's heading draws no + /// rule above it, and each later section keeps the stack's gap. + #[test] + fn memoized_sections_land_where_direct_ones_do() { + let direct = panel_texts(true); + for heading in ["Document", "Rulers & Grids", "Guides", "Snap Options", "Preferences", "Quick Actions", "Snap to Point"] { + assert!(direct.iter().any(|(text, _)| text == heading), "the panel shows {heading:?}: {direct:?}"); + } + let memoized = panel_texts(false); + assert_eq!(memoized, direct, "memoized sections land where direct ones do"); + } + + /// In a panel too short for every section, the sections below the fold still register their controls, so Tab + /// and a screen reader reach them before the panel scrolls. + #[test] + fn sections_below_the_fold_keep_their_controls() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.room(egui::vec2(300.0, 200.0)); + panel.frame(); + panel.frame(); + for name in ["Keyboard Increment", "Scale Strokes & Effects", "Snap to Grid"] { + assert!(panel.shows(name), "the panel registers {name:?} below the fold"); + assert!(panel.rect(name).top() > 200.0, "{name:?} is below the fold of a 200 pt panel"); + } + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -135,4 +367,79 @@ mod tests { assert_eq!(panel.app().session.active().unwrap().doc.units, next, "Enter applies the chosen document unit"); assert_eq!(panel.app().session.general_unit(), next); } + + /// Frames that change nothing the sections show replay them instead of laying them out again. A change one of + /// them reads, from a command run elsewhere, runs it again, and it shows the change. + #[test] + fn idle_frames_replay_the_document_sections() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, document_sections); + panel.room(egui::vec2(400.0, 1000.0)); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames run the memoized sections no more"); + let point = panel.app().ui.view.snap_to_point; + panel.app().run("view.snapToPoint", json!({})).unwrap(); + panel.frame(); + panel.frame(); + assert!(runs() > before, "a new snap setting runs the sections again"); + assert_eq!(panel.app().ui.view.snap_to_point, !point); + assert_eq!(panel.toggled("Snap to Point"), Some(craft::behavior::Mixed::Same(!point)), "and the checkbox shows it"); + panel.app().run("view.rulers", json!({})).unwrap(); + let mut per_frame = Vec::new(); + for _ in 0..12 { + let at = runs(); + panel.frame(); + per_frame.push(runs() - at); + } + // A toggled button animates over the next frames, and a section runs while an animation in it has not ended. + assert_eq!(per_frame[6..], [0; 6], "idle frames after a command run them no more: {per_frame:?}"); + } + + /// The frame that picks new units in the Units menu shows the Keyboard Increment in them: the Preferences + /// section's key reads the General unit after the pick runs, as its lengths do. + #[test] + fn the_frame_that_picks_units_shows_the_increment_in_them() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let initial = app.session.general_unit(); + let mut panel = Panel::new(app, document_sections); + panel.room(egui::vec2(400.0, 1000.0)); + panel.frame(); + let before = panel.value("Keyboard Increment"); + panel.click_role("Units", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + let enter = + |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + panel.frame_with(vec![enter(true), enter(false)]); + assert_ne!(panel.app().session.general_unit(), initial, "Enter applies the chosen unit"); + let picked = panel.value("Keyboard Increment"); + panel.frame(); + let settled = panel.value("Keyboard Increment"); + assert_ne!(settled, before, "the increment shows in the new unit"); + assert_eq!(picked, settled, "the frame of the pick already shows the increment in the new unit"); + } + + /// The memoized sections still take input: a click on Snap to Grid turns it on, once, and Scale Strokes & Effects + /// sets its preference. + #[test] + fn the_memoized_sections_run_their_picks() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let grid = app.ui.view.snap_to_grid; + let scale = app.session.prefs.scale_strokes; + let mut panel = Panel::new(app, document_sections); + panel.room(egui::vec2(400.0, 1000.0)); + panel.frame(); + panel.click("Snap to Grid"); + assert_eq!(panel.app().ui.view.snap_to_grid, !grid, "the click toggles Snap to Grid once"); + panel.click("Scale Strokes & Effects"); + assert_eq!(panel.app().session.prefs.scale_strokes, !scale); + } } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 4a8158364a..dea62a6dfa 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -130,6 +130,154 @@ fn one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top() { assert_eq!(selected(&panel), std::slice::from_ref(&mask), "Edit Clipping Path selects the clipping path"); } +/// Selecting a second object, and going back to one, draws the panel in one pass: the sections are measured for the +/// new selection before they are placed, so the frame is not discarded and drawn again. The frame after each change +/// and a frame with no change take one pass too. +#[test] +fn a_selection_change_draws_the_panel_in_one_pass() { + let mut app = new_app(); + let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 120.0, 20.0, 60.0, 30.0)); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, show); + let passes = |panel: &mut Panel| { + let before = panel.ctx().cumulative_pass_nr(); + panel.frame(); + panel.ctx().cumulative_pass_nr() - before + }; + panel.frame(); + assert_eq!(passes(&mut panel), 1, "a settled frame"); + for round in 0..2 { + for (what, ids) in [("select two", json!([a, b])), ("select one", json!([b])), ("select the other", json!([a]))] { + panel.app().run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(passes(&mut panel), 1, "{what}, round {round}"); + assert_eq!(passes(&mut panel), 1, "the frame after {what}, round {round}"); + } + } +} + +/// The same selection changes in the whole window, with the Properties panel docked: each frame takes one pass, so +/// the canvas and the other panels are drawn once. +#[test] +fn a_selection_change_draws_the_window_in_one_pass() { + let mut app = new_app(); + let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 120.0, 20.0, 60.0, 30.0)); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut passes = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let before = ctx.cumulative_pass_nr(); + let _ = crate::testing::app_frame(app, &ctx, raw); + ctx.cumulative_pass_nr() - before + }; + for _ in 0..4 { + passes(&mut app); + } + assert_eq!(passes(&mut app), 1, "a settled frame"); + for round in 0..2 { + for (what, ids) in [("select two", json!([a, b])), ("select one", json!([b])), ("select the other", json!([a]))] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(passes(&mut app), 1, "{what}, round {round}"); + assert_eq!(passes(&mut app), 1, "the frame after {what}, round {round}"); + } + } +} + +/// Dragging the selected object with the Selection tool, with the Properties panel docked, does not measure the +/// panel's sections on each pointer move, and each frame of the drag takes one pass. The release measures them once +/// for the moved object, and so does an edit made without a drag. +#[test] +fn a_drag_does_not_measure_the_sections_on_each_move() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + app.select_tool("selection"); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + // One frame with `events` → (the passes it took, the section measures it made). + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + events, + ..Default::default() + }; + let (pass, measured) = (ctx.cumulative_pass_nr(), measures()); + let _ = crate::testing::app_frame(app, &ctx, raw); + (ctx.cumulative_pass_nr() - pass, measures() - measured) + }; + for _ in 0..4 { + frame(&mut app, vec![]); + } + let x = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.selection.objects.first().and_then(|id| st.doc.node(*id)).and_then(|n| n.geometric_bounds()).unwrap().x0 + }; + let start_x = x(&app); + let start = app.canvas_view().unwrap().to_screen(craft::behavior::kurbo::Point::new(140.0, 140.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&mut app, vec![Event::PointerMoved(start)]); + assert_eq!(frame(&mut app, vec![button(start, true)]), (1, 0), "the press"); + let mut at = start; + for step in 1..=6 { + at = start + egui::vec2(8.0 * step as f32, 5.0 * step as f32); + assert_eq!(frame(&mut app, vec![Event::PointerMoved(at)]), (1, 0), "move {step} of the drag"); + } + assert_eq!(frame(&mut app, vec![button(at, false)]), (1, 1), "the release measures the moved object's sections once"); + assert!(x(&app) > start_x, "the drag moved the object"); + assert_eq!(frame(&mut app, vec![]).1, 0, "a settled frame"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app, vec![]).1, 1, "an edit without a drag measures the sections"); +} + +/// An edit made while an undo group is open, as a scrubbed field's drag makes, is measured once the group ends, also +/// when ending it does not move the document's revision. +#[test] +fn an_edit_during_a_drag_is_measured_when_the_drag_ends_without_a_new_revision() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let measured = measures(); + let _ = crate::testing::app_frame(app, &ctx, raw); + measures() - measured + }; + for _ in 0..4 { + frame(&mut app); + } + app.run("edit.undoGroup.begin", json!({})).unwrap(); + assert_eq!(frame(&mut app), 0, "opening the group"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app), 0, "an edit inside the group"); + let revision = app.session.active().unwrap().revision; + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().revision, revision, "ending the group keeps the revision"); + assert_eq!(frame(&mut app), 1, "the end of the group measures the edit"); + assert_eq!(frame(&mut app), 0, "a settled frame"); +} + /// Start Global Edit in Quick Actions starts it on the one selected path, the button then reads /// Stop Global Edit, and Escape stops it. Selected type has no Start Global Edit button. #[test] @@ -1084,10 +1232,17 @@ fn quick_actions_follow_the_selection() { } } -/// The panel lists the Quick Actions once per change of what they depend on, not in every frame. +/// The panel lists the Quick Actions once per change of what they depend on, not in every frame. It runs in a process +/// of its own ([`crate::testing::in_own_process`]): what they depend on holds the menus' key, with the installed +/// plug-ins' revision and the fonts' generation, which are the whole process's. #[test] fn quick_actions_are_listed_again_only_after_a_change() { + if !crate::testing::in_own_process("panels::properties::tests::quick_actions_are_listed_again_only_after_a_change") { + return; + } let mut app = new_app(); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. + vectorcraft_text::FontDb::global().family_list(); rect(&mut app, 10.0, 10.0, 40.0, 40.0); rect(&mut app, 80.0, 10.0, 40.0, 40.0); let ctx = crate::testing::ui_context(); @@ -1538,6 +1693,19 @@ fn a_symbol_instance_turns_about_its_registration_point() { assert!(near(bx.reference_point(8), vectorcraft_geom::Point::new(200.0, 160.0)), "the registration point moved to {:?}", bx.reference_point(8)); } +/// With nothing selected the panel's heading is No Selection and "Document" appears once, as the +/// Document section's title, not also as the heading above it. +#[test] +fn nothing_selected_shows_document_once() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let mut panel = Panel::new(app, show); + panel.frame(); + assert!(panel.shows("No Selection")); + let documents = panel.texts().iter().filter(|(text, _)| text == "Document").count(); + assert_eq!(documents, 1, "\"Document\" is shown once"); +} + /// Ruler guides selected on their own (a click on one) show a Guides heading and a Transform /// section, where X moves the vertical ones and Y the horizontal ones; with art selected too, the /// panel shows the art's sections. diff --git a/crates/ui-egui/src/panels/properties/transform_section.rs b/crates/ui-egui/src/panels/properties/transform_section.rs index ad887865dc..042d6165dd 100644 --- a/crates/ui-egui/src/panels/properties/transform_section.rs +++ b/crates/ui-egui/src/panels/properties/transform_section.rs @@ -105,11 +105,12 @@ pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { Row::new().show(ui, |ui, _| panels::corners_link(app, ui)); return; } - // The corners differ in kind: no entry is the value. + // The corners differ in kind: no entry is the value. The select is one number cell wide, as + // the Corner Radius field under it is. let kind = picked.kind.map_or(Mixed::Mixed, Mixed::Same); let entries = panels::corner_entries(); let chosen = Field::new(tl!("Corner")) - .show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).events.committed().copied()) + .show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).number_cell().show(ui).events.committed().copied()) .inner; if let Some(Some(kind)) = chosen { panels::set_picked_corners(app, &picked, json!({"kind": kind})); diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 17fef49e22..ee87567cc0 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -905,11 +905,15 @@ mod tests { let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); let (top, bottom) = profile_outline(r, 1.0, Some(&[(0.0, 1.0, 1.0), (0.5, 10.0, 10.0), (1.0, 1.0, 1.0)])); let all: Vec<_> = top.iter().chain(&bottom).collect(); - assert!(all.iter().all(|p| p.y >= r.top() && p.y <= r.bottom()), "{all:?}"); - let middle = all.iter().map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let (highest, lowest) = all.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y))); + assert!(highest >= r.top() && lowest <= r.bottom(), "the outline stays in its box: {all:?}"); + // How far the outline reaches from the box's middle line. + let reach = |top: &[egui::Pos2], bottom: &[egui::Pos2]| top.iter().chain(bottom).map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let middle = reach(&top, &bottom); assert!((middle - (r.height() / 2.0 - 1.0)).abs() < 1e-3, "the widest point fills the box ({middle})"); let (top, bottom) = profile_outline(r, 1.0, None); - assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); + let plain = reach(&top, &bottom); + assert!(plain > 0.0 && plain <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3, "the plain bar keeps its look ({plain})"); } #[test] diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 515456cad8..ca2b52c605 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -421,6 +421,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); let doc = Arc::clone(&st.doc); let start = dnd::DragStart::of(st); + // The row menu, the drop rules and the drag payload read the document, its reverts and the drag start alone, so + // the browser's rows replay while this version holds. + let host = start.version(st.revision); let document = st.uid; let reverts = st.reverts; let foot = Footer::of(app, &model, held); @@ -448,6 +451,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .row_items(|key| row_items(shown_app, key)) .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts)) .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts)) + .host_version(host) .select(SelectMode::Multi) .search(search) .reveal(focus.clone().map(SwatchKey::Swatch)) diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index df967e9700..4b68266bf1 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -1,3 +1,4 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Weak}; use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params}; @@ -126,6 +127,15 @@ impl DragStart { DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back } } + /// A version of this start in the document's `revision` ([`DocState::revision`]): it changes with + /// the document, its count of File › Revert and its newest undo and redo steps, which are what the + /// panel's row menu, drop rules and drag payload read. + pub(super) fn version(&self, revision: u64) -> u64 { + let mut h = DefaultHasher::new(); + (self.uid, self.reverts, revision, self.steps).hash(&mut h); + h.finish() + } + /// Rows `names` as this document holds them. fn rows(&self, names: &[String]) -> HeldRows { let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect(); diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 4f16980b9a..c14d6cb040 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.swatch_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } /// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find /// narrows them. fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { @@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries { row } fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources { - PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect()) + PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect()) } /// A pattern library's pattern, or a loaded library's, drawn from the library. fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) { diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index f20c725ac0..b3b2ba17e1 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -231,6 +231,47 @@ fn the_footer_menu_buttons_report_that_they_open_a_menu() { } } +/// Every footer action is announced as a button named by its label. Swatch Libraries and Show Swatch Kinds also +/// announce a pressed state that follows the panel: Show Swatch Kinds is pressed while a kind other than All shows, and +/// Swatch Libraries while a swatch library panel is open. The other actions announce no pressed state. +#[test] +fn the_footer_buttons_are_buttons_and_only_the_stateful_ones_announce_pressed() { + use crate::tests::panel_harness::Panel; + use craft::behavior::Mixed; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut panel = Panel::new(app(), show); + for name in [SwatchLibraries::MENU, "Show Swatch Kinds", "Swatch Options", "Delete Swatch", "New Swatch", "New Color Group"] { + assert!(panel.shows_role(name, Role::BUTTON), "{name} is a button"); + } + for name in ["Swatch Options", "Delete Swatch", "New Swatch", "New Color Group"] { + assert_eq!(panel.toggled(name), None, "{name} announces no pressed state"); + } + assert_eq!(panel.toggled("Show Swatch Kinds"), Some(Mixed::Same(false)), "every kind shows"); + assert_eq!(panel.toggled(SwatchLibraries::MENU), Some(Mixed::Same(false)), "no library is open"); + + // Space on the focused footer button opens its menu; the footer sits below the harness's room. + let pick = |panel: &mut Panel, kind: &str| { + panel.focus("Show Swatch Kinds"); + panel.key(Key::Space, Modifiers::NONE); + panel.frame(); + panel.click_role(kind, Role::MENU_ITEM_RADIO); + panel.frame(); + }; + pick(&mut panel, "Show Color Swatches"); + assert_eq!(panel.app().ui.swatches_panel.kind, Kind::Color); + assert_eq!(panel.toggled("Show Swatch Kinds"), Some(Mixed::Same(true)), "a kind filter is on"); + pick(&mut panel, "Show All Swatches"); + assert_eq!(panel.app().ui.swatches_panel.kind, Kind::All); + assert_eq!(panel.toggled("Show Swatch Kinds"), Some(Mixed::Same(false)), "the filter is off again"); + + let id = library_panel::tests::menu_library_ids::(&panel.app()).into_iter().next().expect("a swatch library"); + panel.app().run("window.swatchLibrary", json!({"library": id})).unwrap(); + panel.frame(); + assert_eq!(panel.toggled(SwatchLibraries::MENU), Some(Mixed::Same(true)), "a library panel is open"); +} + /// The footer reads the panel's selection while the browser holds the panel's model: with one swatch selected, Swatch /// Options and Delete Swatch are enabled. #[test] @@ -1623,3 +1664,35 @@ fn the_swatch_libraries_menu_fits_its_rows_like_a_library_panels_menu() { let panel_menu = panel.rect_role("Swatch Libraries Menu", Role::MENU); assert_eq!(footer_menu.width(), panel_menu.width(), "footer menu {footer_menu:?}, library panel menu {panel_menu:?}"); } + +/// Frames that change nothing replay the swatch rows instead of running them again; deleting a swatch and undoing it +/// each run them, the rows show the change, and the frames after replay them again. +#[test] +fn idle_frames_replay_the_swatch_rows() { + use crate::tests::panel_harness::Panel; + use craft::ui::testing::{MemoRun, last_frame_memo_runs}; + let runs = + |panel: &Panel| last_frame_memo_runs(panel.ctx()).iter().filter(|(name, _, run)| name.contains("ListProps") && *run == MemoRun::Ran).count(); + let idle = |panel: &mut Panel, after: &str| { + panel.frame(); + panel.frame(); + for _ in 0..5 { + panel.frame(); + assert_eq!(runs(panel), 0, "an idle frame {after} replays the swatch rows"); + } + }; + let red = "Red, #ed1c24"; + let mut panel = Panel::new(app(), show); + idle(&mut panel, "of a new document"); + assert!(panel.shows(red), "the rows show Red"); + panel.app().run("swatch.delete", json!({"names": ["Red"]})).unwrap(); + panel.frame(); + assert!(runs(&panel) > 0, "deleting a swatch runs the rows"); + assert!(!panel.shows(red), "and they no longer show it"); + idle(&mut panel, "after a delete"); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert!(runs(&panel) > 0, "an undo runs the rows"); + assert!(panel.shows(red), "and they show the swatch again"); + idle(&mut panel, "after an undo"); +} diff --git a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs index bca7cf7852..06c5ce6caa 100644 --- a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs +++ b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs @@ -23,7 +23,9 @@ fn item_commands_run_on_the_clicked_swatch_and_paint_nothing() { let mut app = app(); select_rows(&mut app, &["Black"]); let (before, paint, undo) = (doc(&app), app.session.paint.fill.clone(), undo_steps(&app)); - assert!(enabled(&app, "Red").iter().all(|(_, on)| *on), "every item is enabled on a user swatch"); + let items = enabled(&app, "Red"); + assert_eq!(items.len(), ITEMS.len(), "{items:?}"); + assert!(items.iter().all(|(_, on)| *on), "every item is enabled on a user swatch: {items:?}"); menu(&mut app, "Red", "options"); assert_eq!(dialog_field(&app, KIND, "name"), json!("Red")); assert_eq!((doc(&app), undo_steps(&app)), (before.clone(), undo), "opening the dialog changes nothing"); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e8dbf1a468..c9179cfa06 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -535,7 +535,7 @@ const AT_START: usize = 4; /// A click makes a symbol current and a double click edits it; a symbol drags out to the canvas, /// onto New Symbol (duplicated) or onto Delete Symbol. Art dragged off the canvas and dropped on the /// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol -/// with Alt it redefines that symbol in one undo step. +/// with Alt it redefines that symbol in one undo step, and Alt+Shift also keeps the art. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((doc, revision, uid, reverts, has_sel)) = app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty())) @@ -651,8 +651,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && redefines(&doc, ids) { // Redefine Symbol with the dropped art, which becomes an instance of it, in one - // undo step. Alt art that cannot redefine changes nothing. - run_reported(app, "symbol.update", json!({ "name": target.name, "ids": node_ids(ids) })); + // undo step; Shift keeps the art as ordinary art, as the menu's Redefine Symbol + // does. Alt art that cannot redefine changes nothing. + let mut params = json!({ "name": target.name, "ids": node_ids(ids) }); + if mods.shift { + params["keepArt"] = json!(true); + } + run_reported(app, "symbol.update", params); } } PresetEvent::Menu { target, command, .. } => item_command(app, &target.name, &command), @@ -976,6 +981,10 @@ impl LibraryKind for SymbolLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.symbol_libraries.path(id).map(str::to_string) } + /// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib)) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 262f1d7cdb..23bd444373 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1638,6 +1638,31 @@ fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() { } } +/// Art released with Alt and Shift held on a symbol's tile or row, in each view, redefines that +/// symbol and stays ordinary art in its place, as Redefine Symbol with Shift leaves it, in one +/// undo step. +#[test] +fn alt_shift_art_drop_on_a_symbol_redefines_it_and_keeps_the_art() { + for view in ["thumbnail", "smallList", "largeList"] { + let (app, shape, placed) = alt_drop_doc(view); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let mut p = harness(app, art_and_symbols); + p.drag("Art", "Leaf", Modifiers::ALT | Modifiers::SHIFT); + let mut app = p.app(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added"); + assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step"); + let doc = app.session.active().unwrap().doc.clone(); + let ratio = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height()); + assert!(ratio.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {ratio:?}"); + assert!(doc.node(shape).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })), "{view}: the art keeps its id as a path"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: the art stays ordinary art, not a Leaf instance"); + app.run("edit.undo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo leaves the art"); + } +} + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art holding an instance of the symbol, which the redefine /// refuses, a layer, and art released outside the list. diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index 369006b699..b71ca788a9 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -1016,6 +1016,42 @@ fn the_scale_row_fits_the_panel_width() { } } +/// In a short panel with many format rows, the Export Settings heading and the first row stay inside the panel, and +/// the settings scroll above Export and the footer bar. +#[test] +fn the_settings_scroll_inside_a_short_panel() { + use craft::ui::contract::Role; + let (mut app, _, [a, _]) = app(true); + app.run("assets.add", json!({"ids": [a]})).unwrap(); + let mut p = panel(app); + p.room(egui::vec2(300.0, 1600.0)); + p.frame(); + for _ in 0..7 { + p.click("+ Add Scale"); + } + assert_eq!(settings(&p)["formats"].as_array().unwrap().len(), 8); + p.room(egui::vec2(300.0, 280.0)); + p.frame(); + p.frame(); + let heading = p.painted("Export Settings"); + assert!(!heading.is_empty(), "the Export Settings heading is painted"); + for rect in heading { + assert!(rect.top() >= -0.5 && rect.bottom() <= 280.5, "the Export Settings heading at {rect:?} is outside a 280 pt panel"); + } + let scale = p.rect_role("Scale", Role::COMBO_BOX); + assert!(p.in_view("Scale") && scale.top() >= -0.5, "the first format row at {scale:?} is outside the panel"); + let export = p.rect("Export"); + assert!(export.top() >= -0.5 && export.bottom() <= 280.5, "Export at {export:?} is outside a 280 pt panel"); + // The wheel over the settings brings the last row's Add Scale into view, and Export stays where it was. + for _ in 0..20 { + p.scroll_at(scale.center(), -120.0); + p.frame(); + } + let add = p.rect("+ Add Scale"); + assert!(p.in_view("+ Add Scale") && add.bottom() <= 280.5, "Add Scale at {add:?} is not reachable"); + assert_eq!(p.rect("Export"), export, "Export moved while the settings scrolled"); +} + /// The menu adds the selected artwork as one asset or one per object (an object that is an asset already keeps its /// asset), and is off with no artwork selected. #[test] diff --git a/crates/ui-egui/src/panels/tests_blend.rs b/crates/ui-egui/src/panels/tests_blend.rs index 6aeaaeda67..1653488b5a 100644 --- a/crates/ui-egui/src/panels/tests_blend.rs +++ b/crates/ui-egui/src/panels/tests_blend.rs @@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() { assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends"); // The value typed goes to both; each keeps its own spacing, type and the other value. if name == "Ramp:" { - assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}"); + assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}"); assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift)); } else { - assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}"); + assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}"); assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp)); } assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0))); @@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() { assert!(!p.enabled("Ramp:") && p.enabled("Shift:")); p.type_into("Shift:", "75"); let app = p.app(); - assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift); + assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0)); } #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 77660aedc2..4397e098e6 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -103,23 +103,21 @@ fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { assert_eq!(ui["ui"]["color_wheel"], with(json!({"view": "box", "channel": "green"}))); } -/// The command's errors are translated in the catalogs that translate status and error messages, -/// and each translation keeps the accepted values. +/// The command's errors are shown in the interface language (German and Japanese here), and each +/// translation keeps the accepted values. #[test] fn ui_color_wheel_errors_are_translated() { let errors = [ ("`view` must be wheel or box", &["wheel", "box"][..]), ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), ]; - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); for (error, values) in errors { let shown = crate::i18n::message(lang, error); assert_ne!(shown, error, "{code}"); - assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + let missing: Vec<&str> = values.iter().copied().filter(|v| !shown.contains(v)).collect(); + assert!(missing.is_empty(), "{code}: {shown} lacks {missing:?}"); } } } @@ -147,16 +145,6 @@ fn ui_color_wheel_rejects_other_params() { assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } -/// `ui.colorWheel` answers every junk parameter without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - let mut app = app(json!("#336699"), "hue"); - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } -} - /// The settings survive a JSON round trip of the preferences, and a saved value this build does /// not know reads as the key's default without losing the other preferences. #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index 2f938cc8e2..0b825aedc8 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -347,6 +347,8 @@ fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() { (json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"), (json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"), (json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"model": "rgb", "r": 1e300, "g": 0, "b": 0}}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1e300}}), "`contrastBackground` must be a color or null"), ] { assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs index 8ddf49910a..5d2b67be4d 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -30,8 +30,9 @@ fn app() -> (VectorcraftApp, Vec, Value) { (app, reds, blue) } +/// The accessible name of a color's swatch: its tip, with the line break read as a space. fn label(hex: &str, n: u64) -> String { - format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) + format!("{hex} {}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) } fn has(p: &Panel, label: &str) -> bool { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index 230485922f..b19877ec58 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -38,44 +38,20 @@ fn uncalibrated_cmyk_marks_nothing() { }); } -/// A profile loaded again under the same name can change which colors are printable while the -/// color settings stay the same; the panel keeps drawing through the change. +/// In the wheel's square and in the box, Show Out-of-Gamut Colors changes what the panel draws, +/// and turning it off again draws the panel as it was. #[test] -fn the_grid_is_computed_again_after_a_profile_is_loaded() { - if !crate::testing::in_own_process("panels::tests_color_wheel_gamut::the_grid_is_computed_again_after_a_profile_is_loaded") { - return; +fn the_setting_shades_the_wheel_and_the_box() { + for view in ["wheel", "box"] { + let mut p = Panel::new(app("#3366cc", view, false)); + let off = p.fx.frame_shapes(); + p.run("ui.colorWheel", json!({"gamut": true})); + let on = p.fx.frame_shapes(); + // Compared without printing: a frame holds thousands of shapes. + assert!(on != off, "{view}: the shading is drawn"); + p.run("ui.colorWheel", json!({"gamut": false})); + assert!(p.fx.frame_shapes() == off, "{view}: off draws no shading"); } - let mut p = Panel::new(app("#3366cc", "box", true)); - /// Unregisters the profile when dropped, also after a failed assertion. - struct Unregister(&'static str); - impl Drop for Unregister { - fn drop(&mut self) { - cms::unregister_icc(self.0); - } - } - let name = "Color Wheel Gamut Reload CMYK"; - let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap(); - cms::register_icc(&bytes, Some(name.into())).unwrap(); - let _unregister = Unregister(name); - p.fx.idle(2); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// The wheel's square and the Hue box both show with the setting on. -#[test] -fn the_wheel_and_the_hue_box_shade_the_same_cells() { - let mut p = Panel::new(app("#3366cc", "wheel", true)); - assert!(p.fx.by_label("Saturation and brightness").is_some()); - p.run("ui.colorWheel", json!({"view": "box"})); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// With Show Out-of-Gamut Colors off, the panel still draws and the setting reads off. -#[test] -fn with_the_setting_off_no_grid_is_computed() { - let p = Panel::new(app("#3366cc", "box", false)); - assert!(!p.app().ui.color_wheel.gamut); - assert!(p.fx.by_label("Color box").is_some()); } /// `ui.colorWheel {gamut}` sets the setting and keeps the others; a key set to null keeps its value diff --git a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs index 8a8ddf4768..be2cf16ae3 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs @@ -114,17 +114,14 @@ fn ui_color_wheel_sets_the_harmony_and_its_rule() { assert_eq!(got["harmonyRule"], json!("splitComplementary")); } -/// The errors are translated in the catalogs that translate status and error messages, and each +/// The errors are shown in the interface language (German and Japanese here), and each /// translation keeps the key and the accepted values. #[test] fn ui_color_wheel_harmony_errors_are_translated() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let flag = app.run("ui.colorWheel", json!({"harmony": 1})).unwrap_err(); let rule = app.run("ui.colorWheel", json!({"harmonyRule": "shades"})).unwrap_err(); - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); let shown = crate::i18n::message(lang, &flag); assert!(shown != flag && shown.contains("`harmony`"), "{code}: {shown}"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e2c5a62b80..5c1920d8c4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { quick_click(&mut p, rail.rect.center()); let (hex, opacity) = first_stop(&p); assert_eq!(hex, "#336699", "the text applies"); - assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}"); + assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}"); } /// A press on the opacity slider that takes the focus from an edited field applies the text and diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 507b8280e2..58cb9a84b4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); } /// A value this build does not read keeps the rest of the preferences and reads as the default. @@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); let labels = undo_labels(&p.app()); assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000"); @@ -433,14 +433,3 @@ fn the_row_is_gray_with_nothing_selected_and_on_type() { let p = Panel::new(app); assert!(disabled(&p)); } - -/// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - for mut app in [app(), VectorcraftApp::new(Session::new(), Default::default())] { - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } - } -} diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index af34acbd8e..d6be853ad4 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -681,6 +681,94 @@ fn placement_options_dialog_sets_the_options() { assert_eq!(r["placement"], json!({"preserve": "fit", "align": "bottomRight", "clip": false})); } +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_changes() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-selection"); + let (app, first, _) = app(&dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + let placement = |app: &mut VectorcraftApp, id: u64| app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"].clone(); + let second_before = placement(&mut app, second); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + app.run("select.set", json!({"ids": [second]})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + + assert_eq!(placement(&mut app, second), second_before, "the image selected after the dialog opened keeps its options"); + assert_eq!(placement(&mut app, first)["preserve"], json!("fit"), "OK applies to the image the dialog opened on"); +} + +/// Two linked images, the first with preserve `fill` and the second with `bounds`, in a window. +fn two_links(dir: &Folder) -> (VectorcraftApp, u64, u64) { + let (app, first, _) = app(dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + (app, first, second) +} + +fn preserve_of(app: &mut VectorcraftApp, id: u64) -> serde_json::Value { + app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"]["preserve"].clone() +} + +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_is_emptied() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deselect"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("select.set", json!({"ids": []})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert!(open_dialogs(&app).is_empty(), "OK closes the dialog"); + assert_eq!(preserve_of(&mut app, first), json!("fit")); + assert_eq!(preserve_of(&mut app, second), json!("bounds")); +} + +#[test] +fn placement_options_dialog_changes_nothing_when_a_link_it_opened_on_is_deleted() { + use craft::ui::dialog::HeldOk; + + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deleted"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("edit.clear", json!({})).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + let refused = app.dialogs().unwrap().with(|h| matches!(h.held_state(open[0].id), Some(HeldOk::Refused(_)))); + assert!(refused, "OK is refused and the dialog stays open"); + assert_eq!(preserve_of(&mut app, second), json!("bounds"), "the selected image keeps its options"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); +} + +#[test] +fn placement_options_dialog_applies_to_the_ids_it_was_given() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-ids"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({"ids": [second]})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert_eq!(preserve_of(&mut app, second), json!("fit")); + assert_eq!(preserve_of(&mut app, first), json!("fill"), "the selected image keeps its options"); +} + #[test] fn properties_shows_the_selected_image_and_its_link_actions() { let dir = Folder::new("props"); diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index ecac244136..d5837ffed5 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -101,6 +101,8 @@ fn dialog_lengths_show_in_the_general_unit() { window.type_text("10 mm"); window.key(egui::Key::Tab, egui::Modifiers::NONE); confirm_dialog(&mut window.app()); + // The Move dialog holds its OK, so it leaves the stack in the next frame. + window.frame(); let square = { let app = window.app(); let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/panels/transform/shape.rs b/crates/ui-egui/src/panels/transform/shape.rs index f9cc3a64ab..8530a90390 100644 --- a/crates/ui-egui/src/panels/transform/shape.rs +++ b/crates/ui-egui/src/panels/transform/shape.rs @@ -229,12 +229,13 @@ fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { } } -/// The polygon's Corner type select, blank while `kind` is `None` (the corners differ). +/// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the +/// number fields of its column are. fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option) { let entries = corner_entries(); let mut edit = None; Field::new(tl!("Corner")).show(ui, |ui, _| { - edit = Some(Select::new(tl!("Corner"), Bind::given(kind.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui)); + edit = Some(Select::new(tl!("Corner"), Bind::given(kind.map_or(Mixed::Mixed, Mixed::Same)), &entries).number_cell().show(ui)); }); if let Some(edit) = edit { apply_edits(app, &edit, EditPath::Scope, |app, k, _| set_live_shape(app, json!({ "kind": k }))); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index a5f37234e1..fa4b550289 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -246,6 +246,66 @@ fn unlinked_corner_labels_start_in_one_column() { } } +/// An app with a live rectangle selected whose Corner Radius is linked. +fn linked_rectangle_app() -> VectorcraftApp { + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap(); + set_pref(&mut app, "singleCornerRadius", true); + app +} + +/// An app with the Direct Selection tool chosen and corner 2 of a star selected. +fn star_corner_app() -> VectorcraftApp { + let mut app = new_app(); + let star = app.run("shape.star", json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + app +} + +/// A Corner select in a column of number fields is one number cell wide, as the Corner Radius field of its column +/// is: a live rectangle's linked Corner and a live polygon's Corner, in the Transform panel and the Properties panel's +/// Transform section, and the Corner of a path's Direct-Selected corners in the Properties panel. Each still opens, +/// and Enter sets the kind highlighted in its list on the corner it reads. +#[test] +fn corner_selects_are_as_wide_as_the_corner_radius_field() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_doc::LiveCorners; + use vectorcraft_geom::shapes::CornerKind; + type Draw = fn(&mut VectorcraftApp, &mut Ui); + /// A case's name, the app it starts from, the panel it draws and the corner whose kind it reads. + type Case = (&'static str, fn() -> VectorcraftApp, Draw, usize); + let transform = show as Draw; + let properties = crate::panels::properties::transform_section as Draw; + let cases: [Case; 5] = [ + ("Transform panel, linked rectangle", linked_rectangle_app, transform, 0), + ("Properties panel, linked rectangle", linked_rectangle_app, properties, 0), + ("Transform panel, polygon", || polygon_app(6), transform, 0), + ("Properties panel, polygon", || polygon_app(6), properties, 0), + ("Properties panel, Direct-Selected corner", star_corner_app, crate::panels::properties::show, 2), + ]; + for (case, app, draw, corner) in cases { + let mut p = Panel::new(app(), draw); + let select = p.rect_role("Corner", Role::COMBO_BOX); + let field = p.rect_role("Corner Radius", Role::SPIN_BUTTON); + assert!( + (select.width() - field.width()).abs() < 0.5, + "{case}: the Corner select is {} wide, the Corner Radius field {}", + select.width(), + field.width() + ); + let kind = |p: &Panel| LiveCorners::of(&first_selected(&p.app()).unwrap()).unwrap().kind(corner); + assert_eq!(kind(&p), CornerKind::ALL[0], "{case}"); + let undo = undo_depth(&p.app()); + p.click_role("Corner", Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + assert_eq!(kind(&p), CornerKind::ALL[1], "{case}: Enter sets the highlighted kind"); + assert_eq!(undo_depth(&p.app()), undo + 1, "{case}: the kind is one undo step"); + } +} + /// A corner kind set with no live rectangle selected leaves the selected polygon, the document and /// its undo history as they are. #[test] diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 193837507e..8b814eac71 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -380,11 +380,13 @@ fn mask_items(mask: Option<&OpacityMask>, can_make: bool) -> [(&'static str, &'s } /// The masked object's mask, also while editing it (the selection then is the mask art), whether the -/// object controls apply, and whether Make is possible. +/// object controls apply, and whether Make is possible. Make's check runs only for an object without a mask, the one +/// case whose rows read it ([`mask_items`]). fn menu_context(app: &VectorcraftApp) -> (Option>, bool, bool) { let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some()); - let n = first_node(app, &app.session.transparency_info()); - let can_make = n.is_some() && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask"); + let n = app.session.transparency_target().and_then(|id| super::layers::node_arc(&app.session.active()?.doc, id)); + let unmasked = n.as_ref().is_some_and(|n| n.extras().mask.is_none()); + let can_make = unmasked && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask"); (n, object_controls(app, editing), can_make) } @@ -452,6 +454,30 @@ mod tests { app } + /// The menu's states check Make Opacity Mask only for a first object without a mask: a masked one shows Release, + /// Disable and Unlink instead, and Make dimmed without its check. + #[test] + fn the_menu_checks_make_only_for_an_object_without_a_mask() { + let mut app = new_app(); + let rectangle = |app: &mut VectorcraftApp, x| run_cmd(app, "shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})); + let masked = rectangle(&mut app, 10)["id"].clone(); + let art = rectangle(&mut app, 12)["id"].clone(); + let plain = rectangle(&mut app, 50)["id"].clone(); + run_cmd(&mut app, "transparency.makeOpacityMask", json!({"ids": [masked, art]})); + // How many times the states asked for Make's check, and whether Make is enabled. + let asked = |app: &VectorcraftApp| { + let mut states = CommandStates::new(); + crate::menus::WHY_OFF_ASKED.with_borrow_mut(Vec::clear); + menu_states(app, &mut states); + let make = crate::menus::WHY_OFF_ASKED.take().iter().filter(|a| *a == "transparency.makeOpacityMask").count(); + (make, states.get(&CommandRef::new("transparency.makeOpacityMask")).is_some_and(CommandState::is_enabled)) + }; + run_cmd(&mut app, "select.set", json!({"ids": [masked]})); + assert_eq!(asked(&app), (0, false), "a masked object: Make is dimmed without its check"); + run_cmd(&mut app, "select.set", json!({"ids": [plain]})); + assert_eq!(asked(&app), (1, true), "an object without a mask: Make's check runs once"); + } + #[test] fn transparency_shows_each_selected_symbol_parts_values() { let mut app = new_app(); diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 972e907fea..9d1cc5be02 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -445,7 +445,7 @@ fn spawn_labeled( /// the file is placed unless the tool has a preview open (the Flare tool after its center drag). pub fn poll(app: &mut VectorcraftApp) { settle_swatch_paste(app); - while !app.any_dialog_open() + while !app.asking_dialog_open() && !app.session.in_interaction() && !(app.session.tool_busy() && app.session.pointer_held()) && let Some(p) = app.placing.pending.first() diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index fb75d86663..dc6a19e0fc 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -1980,6 +1980,7 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert_eq!(progress(&mut app, &ctx), "", "nothing placing"); let slow_path = saved("progress", "slow.png", &picture(Png, 100, 100)); @@ -2002,10 +2003,12 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { start(&mut app, &json!({"path": next_path, "at": [200, 150]}), false).unwrap(); let texts = progress(&mut app, &ctx); assert!(texts.contains("Placing slow.png…") && texts.contains("waiting"), "{texts}"); + assert!(app.any_dialog_open()); - // Release and finish + // Releasing the read applies both files without dismissing the progress window first. drop(go); placed(&mut app); + assert_eq!(progress(&mut app, &ctx), "", "completion closes progress"); } /// #5930: cancelling a place aborts the operation, drops the parsed asset, leaves the document diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 067302ddcb..a5be54af01 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -458,7 +458,7 @@ pub fn poll(app: &mut VectorcraftApp) { poll_checks(app); let mut i = 0; while let Some(r) = app.plugin_runs.running.get(i) { - let dialog = app.any_dialog_open() || app.session.script_running(); + let dialog = app.asking_dialog_open() || app.session.script_running(); let ended = match &r.backend { Backend::Thread(_) if dialog => None, Backend::Worker(..) if dialog => watch_worker(app, i), diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 3a951fb6cb..847610adb4 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, PoisonError}; use craft::host::{PickKind, PickRequest}; use craft::theme::Rgba; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::form::{SliderField, SliderFieldLayout}; use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PathSetting, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; @@ -26,6 +26,21 @@ use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; /// The pixel size every point-stored length field of this port uses. const PIXELS_PER_INCH: f64 = 72.0; +/// The preferences that a dialog's Don't Show Again box turns off, one per dialog; General › Reset All Warning +/// Dialogs turns each of them back on. The button follows the last one's row. +pub(super) const WARNING_DIALOGS: &[&str] = &["showExternalScriptWarning"]; + +/// The row key of the Reset All Warning Dialogs button. +const RESET_WARNINGS_KEY: &str = "resetWarningDialogs"; + +/// Turns the warning preferences `keys` back on in the draft, as Reset All Warning Dialogs does; OK or Apply writes +/// them. +pub(super) fn reset_warning_dialogs(w: &mut PrefsWindow, keys: &[&str]) { + for key in keys { + w.set_row(key, &json!(true)); + } +} + /// The model of the open window: the app, and the window taken out of it for the pass. pub(super) struct Live<'a> { pub(super) app: &'a mut VectorcraftApp, @@ -264,6 +279,10 @@ impl Live<'_> { let english = "Script File Access revoke read write file folder"; groups.add(sp.section, self.row(script_access::KEY, tl!("Script File Access"), english, RowKind::CustomRows)); } + if WARNING_DIALOGS.last() == Some(&sp.key) { + let english = "Reset All Warning Dialogs don't show again"; + groups.add(sp.section, self.row(RESET_WARNINGS_KEY, "", english, RowKind::Custom)); + } } if cat == PREF_CATEGORIES[0] { let tools = self.row("prefsFile", "", "export import reset preferences", RowKind::Custom); @@ -370,6 +389,14 @@ impl PreferencesModel for Live<'_> { script_access::show(self.app, &mut self.w.script_access, ui); false } + RESET_WARNINGS_KEY => { + let turned_off: Vec<&str> = WARNING_DIALOGS.iter().copied().filter(|k| !self.bool_of(k)).collect(); + if Button::new(tl!("Reset All Warning Dialogs")).enabled(!turned_off.is_empty()).show(ui).clicked() { + reset_warning_dialogs(self.w, &turned_off); + return true; + } + false + } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); let web = crate::io::is_web(self.app); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index fc61192b84..5b15a52f69 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1536,3 +1536,56 @@ fn script_file_access_revoke_names_the_whole_path() { } let _ = std::fs::remove_dir_all(store.parent().unwrap()); } + +/// One frame of the Reset All Warning Dialogs row in the window's context with `events` → the texts it drew, each +/// with its place. +fn reset_warnings_frame(a: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let ctx = a.ui_ctx.clone().expect("a window context"); + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), events, ..Default::default() }; + let out = crate::testing::part_frame(a, &ctx, raw, |a, ui| { + let Some(mut w) = a.prefs.take() else { return }; + let _ = model::Live { app: &mut *a, w: &mut w }.custom_row(ui, "resetWarningDialogs"); + a.prefs = Some(w); + }); + crate::tests_removeanchors::shapes_text(&crate::tests_labels::flat_painted_shapes(&out.shapes)) +} + +/// Clicks Reset All Warning Dialogs with the pointer. +fn click_reset_warnings(a: &mut VectorcraftApp) { + reset_warnings_frame(a, vec![]); + let texts = reset_warnings_frame(a, vec![]); + let label = "Reset All Warning Dialogs"; + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + reset_warnings_frame(a, vec![egui::Event::PointerMoved(at)]); + reset_warnings_frame(a, vec![press(true)]); + reset_warnings_frame(a, vec![press(false)]); +} + +/// General shows Reset All Warning Dialogs beside the warning a Don't Show Again box turned off. With the warning +/// off, the button turns it back on in the window and OK saves it; with every warning on, the button is dimmed and +/// a click leaves the row untouched. +#[test] +fn reset_all_warning_dialogs_turns_a_dismissed_warning_back_on() { + let mut a = app(); + a.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).unwrap(); + open(&mut a, Some("General")); + let rows: Vec<(String, String)> = with_pages(&mut a, |pages| { + let general = pages.iter().find(|p| p.id == "General").expect("a General page"); + general.groups.iter().flat_map(|g| g.rows.iter().map(|r| (g.title.unwrap_or_default().to_string(), r.key.to_string()))).collect() + }); + let at = |key: &str| rows.iter().position(|(_, k)| k == key).unwrap_or_else(|| panic!("no {key} in {rows:?}")); + let (warning, reset) = (at("showExternalScriptWarning"), at("resetWarningDialogs")); + assert!(warning < reset && rows[warning].0 == rows[reset].0, "the button follows the warning's row in its section: {rows:?}"); + + click_reset_warnings(&mut a); + assert_eq!(field(&a, "showExternalScriptWarning"), json!(true), "the window shows the warning on"); + assert!(!a.session.prefs.show_external_script_warning, "nothing is saved before OK"); + confirm(&mut a).unwrap(); + assert!(a.session.prefs.show_external_script_warning, "OK saves the warning on"); + + open(&mut a, Some("General")); + click_reset_warnings(&mut a); + assert!(!a.prefs.as_ref().unwrap().touched.contains("showExternalScriptWarning"), "a dimmed button changes nothing"); +} diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 863c94673d..61860ee915 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -4,9 +4,15 @@ //! it, or saves the PDF when asked to (`toFile`, `path`) or when there is no print service; a //! PostScript file (`format: "postscript"`, or a `.ps` path) is always saved. `print.printers` //! lists the printers. +//! +//! A script run started in the app gets the printers of a service that lets scripts print +//! ([`PrintService::scripts_may_print`], the desktop's), as names only. The jobs a script prepares +//! for them are sent after the run's changes are kept and the person approves them +//! ([`crate::dialogs::script_run::PRINT_KIND`], [`send_script_prints`]). use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::script::printing::{PreparedPrint, Printers}; use crate::{VectorcraftApp, io}; @@ -48,6 +54,11 @@ pub trait PrintService { fn has_setup(&self) -> bool { false } + /// Whether scripts may list this service's printers and send jobs to them once the person + /// approves them. The browser's print dialog picks its own printer, so the web's does not. + fn scripts_may_print(&self) -> bool { + false + } /// Setup…: open the system's settings of `printer` (`None`: the printers). fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> { Err("there are no printer settings to open here".into()) @@ -61,6 +72,71 @@ pub fn printers(app: &mut VectorcraftApp) -> Value { json!({ "printers": printers, "service": app.services.print.is_some(), "setup": setup }) } +/// The printers a script run may print to: the print service's, by name, when it lets scripts +/// print; `None` otherwise. +pub fn script_printers(app: &mut VectorcraftApp) -> Option { + let service = app.services.print.as_mut().filter(|s| s.scripts_may_print())?; + let for_printer = !service.turns_landscape(); + Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer)) +} + +/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to +/// ([`script_printers`]), and only that run lists them. +pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { + if id == "script.run" { + app.session.script_printers = script_printers(app); + } + let r = app.session.execute(id, params).map_err(|e| e.to_string()); + app.session.script_printers = None; + r +} + +/// The error for a script's jobs when the print service does not let scripts print. +const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent"; + +/// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer +/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or +/// `{background: true}` while the desktop's worker sends them. +pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result { + let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?; + let listed: Vec = service.printers().into_iter().map(|p| p.name).collect(); + if let Some(gone) = jobs.iter().find(|j| !listed.contains(&j.printer)) { + return Err(format!("The printer {} is no longer installed: the script's print jobs were not sent", gone.printer)); + } + let count = jobs.len(); + if let Some(submit) = service.shared_print() { + return crate::background::run( + app, + true, + "Printing from a script".into(), + None, + move |_| send_each(&mut |job| submit(job), &jobs).map(|notes| json!({ "notes": notes })), + move |app, result| { + let notes = result?; + app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default()); + Ok(json!({ "sent": count })) + }, + ); + } + let notes = send_each(&mut |job| service.print(job), &jobs)?; + app.status(notes.last().cloned().unwrap_or_default()); + Ok(json!({ "sent": count })) +} + +/// Gives each of `jobs` to `submit`, in order, stopping at the first that fails. → what each one +/// gave, or the error, which says how many were sent before it. +fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result, jobs: &[PreparedPrint]) -> Result, String> { + let mut notes = Vec::new(); + for (sent, job) in jobs.iter().enumerate() { + match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) { + Ok(note) => notes.push(note), + Err(e) if sent == 0 => return Err(e), + Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())), + } + } + Ok(notes) +} + /// `file.print` with settings: print the active document with `settings` (over the document's, or /// over those of the print preset `preset` names) on `printer` (default: the system's default), or /// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a diff --git a/crates/ui-egui/src/retype_runs.rs b/crates/ui-egui/src/retype_runs.rs index 81f774d5d3..c51c5a6a8f 100644 --- a/crates/ui-egui/src/retype_runs.rs +++ b/crates/ui-egui/src/retype_runs.rs @@ -130,7 +130,7 @@ fn stop(app: &mut VectorcraftApp) { /// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while /// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`]. pub fn poll(app: &mut VectorcraftApp) { - if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { return; } let Some(r) = &app.retype_runs.running else { return }; diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index ee469adf18..16fff70c80 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -2,7 +2,8 @@ //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with //! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, -//! waits for the person's answer. +//! waits for the person's answer. A run that prepared jobs for a printer ends with the question +//! before they are sent. use serde_json::{Value, json}; use vectorcraft_engine::WindowView; @@ -14,6 +15,7 @@ use crate::dialogs::script_window; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { startup_failures(app); + script_run::ask_print(app); if !app.session.script_running() { return; } @@ -47,6 +49,8 @@ pub fn poll(app: &mut VectorcraftApp) { if !crate::panels::actions::after_journaled_edit(app) { app.status(format!("Ran {name}")); } + // The jobs it prepared for a printer wait for the person's answer. + script_run::ask_print(app); } Err(e) => ended_with_error(app, startup, e.to_string()), } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 56489b2726..997a738bbe 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -225,7 +225,7 @@ fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { /// An arrow nudge of the window or of a tool that left it. `direction` points the way of the arrow. In /// Presentation Mode Left and Right step the artboard and nothing moves; with only type selected, Alt steps the -/// type's spacing; otherwise the selection moves (Shift ×10, Alt copies, `patterns_only` moves pattern fills only). +/// type's spacing; otherwise the selection moves (Shift ×10, Ctrl/Cmd ÷10, Alt copies, `patterns_only` moves pattern fills only). pub(crate) fn nudge(app: &mut VectorcraftApp, direction: egui::Vec2, mods: Mods, patterns_only: bool) { if app.ui.screen_mode == 3 { if direction.x != 0.0 { @@ -249,7 +249,7 @@ pub(crate) fn nudge(app: &mut VectorcraftApp, direction: egui::Vec2, mods: Mods, return; } if app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { - let mut params = json!({"dx": f64::from(direction.x), "dy": f64::from(direction.y), "big": mods.shift, "copy": mods.alt}); + let mut params = json!({"dx": f64::from(direction.x), "dy": f64::from(direction.y), "big": mods.shift, "fine": mods.cmd, "copy": mods.alt}); if patterns_only { params["objects"] = json!(false); params["patterns"] = json!(true); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index f5cd51ebb5..9b441b1f67 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -210,6 +210,18 @@ fn editing_hi() -> (VectorcraftApp, u64) { (app, id) } +/// [`editing_hi`] in the window of `ctx`, which a test can reuse for a new app at each step, after the frames +/// [`typing_ready`] runs. +fn editing_hi_in(ctx: &egui::Context) -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + key_frame(&mut app, ctx, vec![]); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + edit(&mut app, 2, 2); + idle(&mut app, ctx, 2); + (app, id) +} + /// Starts editing the selected type object with the Type tool and selects `start..end`. fn edit(app: &mut VectorcraftApp, start: u64, end: u64) { app.select_tool("type"); @@ -901,22 +913,33 @@ fn alt_chords_type_special_characters_while_editing_text() { return; } let mut wrong = vec![]; + // A new app for each chord, all in one window. + let ctx = crate::testing::ui_context(); for (key, shift, own, character) in ALT_CHARACTER_CHORDS { for typed in [None, Some(own), Some(own.to_uppercase().as_str())] { - let (mut app, id) = editing_hi(); - let ctx = typing_ready(&mut app); + let (mut app, id) = editing_hi_in(&ctx); key_frame(&mut app, &ctx, alt_press(key, shift, typed)); let case = format!("{key:?} shift={shift} text={typed:?}"); let text = text_and_layers(&mut app, id).0; if text != format!("Hi{character}") { wrong.push(format!("{case}: text = {text:?}")); - continue; - } - app.session.execute("edit.undo", &json!({})).unwrap(); - let undone = text_and_layers(&mut app, id).0; - if undone != "Hi" { - wrong.push(format!("{case}: after Undo = {undone:?}")); + } else { + app.session.execute("edit.undo", &json!({})).unwrap(); + let undone = text_and_layers(&mut app, id).0; + if undone != "Hi" { + wrong.push(format!("{case}: after Undo = {undone:?}")); + } } + // The window keeps a key held from one app to the next: the release makes the next chord a new press. + let m = if shift { Modifiers::ALT | Modifiers::SHIFT } else { Modifiers::ALT }; + key_frame( + &mut app, + &ctx, + vec![ + egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: m }, + egui::Event::ModifiersChanged(Modifiers::NONE), + ], + ); } } assert!(wrong.is_empty(), "{wrong:#?}"); @@ -1149,6 +1172,24 @@ fn selected_vertical_area_and_path_type_use_vertical_spacing_chords() { } } +/// #5258: Ctrl/Cmd+arrow nudges the selection by a tenth of the keyboard increment, and Shift+Ctrl/Cmd+arrow by one +/// increment, one undo step each. +#[test] +fn command_arrows_nudge_by_a_tenth_of_the_keyboard_increment() { + let mut app = new_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let x0 = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x0; + let ctx = ready(&mut app); + let before = undo_len(&app); + for (m, x, n) in [(cmd(), 20.1, 1), (cmd() | Modifiers::SHIFT, 21.1, 2), (Modifiers::NONE, 22.1, 3)] { + key_frame(&mut app, &ctx, tap(Key::ArrowRight, m)); + assert!((x0(&app) - x).abs() < 1e-9, "{m:?}: {}", x0(&app)); + assert_eq!(undo_len(&app), before + n, "{m:?}"); + } +} + /// Alt+arrows step a selected type object instead of copying it; a rectangle with Alt is copied. #[test] fn alt_arrows_step_selected_type_object() { @@ -1797,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { // the key is still running when Cancel stops it, however long the frames take. let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); + // The clock stands still: the run's progress window, which opens once the run is old enough + // and takes the keys, stays closed however slowly the frames run. + app.now_override = Some(0.0); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 6098a8467a..89a74801bc 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -22,10 +22,21 @@ pub(crate) fn install(ctx: &egui::Context) { /// `app` shown in a window of its own: its context is the one every frame of the test runs on, so its dialogs open on /// the window's host, focus and drags last from frame to frame, and the access tree is on for the tests that find a /// control by its role. -pub(crate) fn windowed(mut app: crate::VectorcraftApp) -> crate::VectorcraftApp { +pub(crate) fn windowed(app: crate::VectorcraftApp) -> crate::VectorcraftApp { + windowed_in(app, &window_context()) +} + +/// The context of a window [`windowed`] shows an app in, with the access tree on. A test that makes a new app for each +/// item can show each one in the same window with [`windowed_in`]. +pub(crate) fn window_context() -> egui::Context { let ctx = ui_context(); ctx.enable_accesskit(); - app.ui_ctx = Some(ctx); + ctx +} + +/// `app` shown in the window of `ctx`, as [`windowed`] shows it in a window of its own. +pub(crate) fn windowed_in(mut app: crate::VectorcraftApp, ctx: &egui::Context) -> crate::VectorcraftApp { + app.ui_ctx = Some(ctx.clone()); app } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 70eba60a17..4d6ed47b17 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -23,6 +23,7 @@ mod numfields; mod overprint; mod paintchips; pub(crate) mod panel_harness; +mod panel_scroll; mod pastechords; mod pathtype; mod pdfoutput; @@ -33,6 +34,7 @@ mod plugins; mod printps; mod printtiling; mod quickpenbar; +mod quickpenwheel; mod recolor; mod recovery; pub(super) mod removeanchors; @@ -44,6 +46,7 @@ mod saveext; mod screenmode; mod script_check; mod script_dialogs; +mod script_print; mod script_run; mod script_window; mod scripts_menu; diff --git a/crates/ui-egui/src/tests/background.rs b/crates/ui-egui/src/tests/background.rs index fe90152db4..98cb20bbc9 100644 --- a/crates/ui-egui/src/tests/background.rs +++ b/crates/ui-egui/src/tests/background.rs @@ -28,6 +28,18 @@ impl Gate { std::thread::sleep(std::time::Duration::from_millis(1)); } } + + /// Open the gate once this thread starts to wait for a background job ([`background::wait_until`]). + /// The flag returned says whether it did. + pub(crate) fn open_on_wait(&self) -> std::rc::Rc> { + let (gate, opened) = (self.clone(), std::rc::Rc::new(std::cell::Cell::new(false))); + let flag = opened.clone(); + background::ON_WAIT.set(Some(Box::new(move || { + flag.set(true); + gate.open(); + }))); + opened + } } /// Gives `app` a window host over `jobs`, as the window installs it, so its background work runs @@ -347,14 +359,10 @@ fn quitting_waits_for_background_saves() { let (mut app, files) = app(gate.clone()); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); app.run("file.save", json!({"path": "/docs/q.vectorcraft"})).unwrap(); - let opener = gate.clone(); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(50)); - opener.open(); - }); + let waited = gate.open_on_wait(); // Without waiting, the document would still count as modified and Quit would ask about it. let r: Value = app.run("app.quit", json!({})).unwrap(); - release.join().unwrap(); + assert!(waited.get(), "Quit waited for the save"); assert!(r.is_null(), "{r}"); assert_eq!(app.ui.status, "quit"); assert_eq!(written(&files), ["/docs/q.vectorcraft"]); diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index b8c6972dee..ad11b25441 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -681,6 +681,72 @@ impl CanvasMenu { } } +#[test] +fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() { + let mut app = app(); + let path = rect(&mut app, 50.0, 50.0); + assert!(!has(&app, "Create Outlines"), "a path alone has no text to outline"); + app.run("select.none", json!({})).unwrap(); + assert!(!has(&app, "Create Outlines"), "an empty selection has no text to outline"); + + let point = app.run("text.create", json!({"x": 180, "y": 80, "text": "One"})).unwrap()["id"].as_u64().unwrap(); + assert!(has(&app, "Create Outlines"), "point text offers the action"); + let area = + app.run("text.create", json!({"x": 180, "y": 100, "text": "Two", "area": {"width": 120, "height": 80}})).unwrap()["id"].as_u64().unwrap(); + assert!(has(&app, "Create Outlines"), "area text offers the action"); + app.run("select.set", json!({"ids": [path.0, point, area]})).unwrap(); + + let mut canvas = CanvasMenu::new(app); + canvas.right_click(100.0, 100.0); + let tree = canvas.fixture.tree(); + let item = canvas + .fixture + .by_role(craft::ui::contract::Role::MENU_ITEM) + .into_iter() + .find(|item| tree.name_of(item.node).is_some_and(|name| name.starts_with("Create Outlines"))) + .expect("the rendered canvas menu offers Create Outlines"); + canvas.fixture.click(&item); + crate::testing::fixture_input(&mut canvas.app.borrow_mut(), &mut canvas.fixture); + canvas.frame(vec![]); + + let mut app = canvas.app.borrow_mut(); + let st = app.session.active().unwrap(); + assert!(st.doc.node(path).is_some()); + for id in [point, area] { + assert!(st.doc.node(NodeId(id)).is_none(), "the original text was replaced"); + } + assert_eq!( + st.selection.objects.iter().filter(|&&id| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Group { .. }))).count(), + 2, + "both text objects became selected groups" + ); + app.run("edit.undo", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + for id in [point, area] { + assert!(matches!(doc.node(NodeId(id)).map(|n| &n.kind), Some(NodeKind::Text(_))), "one Undo restored both text objects"); + } +} + +#[test] +fn create_outlines_is_offered_for_a_selected_group_with_nested_text() { + let mut app = app(); + let a = rect(&mut app, 20.0, 20.0); + let b = rect(&mut app, 150.0, 20.0); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let paths = app.session.active().unwrap().selection.objects[0]; + assert!(!has(&app, "Create Outlines"), "a group of paths has no text to outline"); + + let text = app.run("text.create", json!({"x": 180, "y": 175, "text": "Nested"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [paths.0, text]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let inner = app.session.active().unwrap().selection.objects[0]; + let c = rect(&mut app, 280.0, 20.0); + app.run("select.set", json!({"ids": [inner.0, c.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert!(has(&app, "Create Outlines"), "the selected outer group contains text"); +} + /// #5267: a right-click on a stroked object offers Outline Stroke, which runs /// `object.path.outlineStroke` (the Object › Path item) and leaves filled art; an object with no /// stroke to outline has no such item. diff --git a/crates/ui-egui/src/tests/cut.rs b/crates/ui-egui/src/tests/cut.rs index 4732a6347b..995f87564a 100644 --- a/crates/ui-egui/src/tests/cut.rs +++ b/crates/ui-egui/src/tests/cut.rs @@ -11,7 +11,7 @@ fn the_cut_tools_have_their_own_icons_and_toolbar_slot() { let info = vectorcraft_tools::tool_info(tool).unwrap(); assert_eq!(icons::tool_icon(info.icon), icon); // The app registers its icons at start; a test run alone in its process must too. - craft::ui::primitives::register_app_icons(&icons::APP_ICONS); + icons::register(); assert!(craft::ui::primitives::has_icon(&IconId::new(icon)), "{icon}"); assert!(crate::toolbar::BASIC.iter().flat_map(|(_, slots)| slots.iter()).any(|s| s.contains(&tool) && s.contains(&"knife"))); } diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 9a6ce5421c..28d573d09b 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -86,6 +86,11 @@ fn preview_changes_the_text_live_and_only_a_choice_is_a_step() { let before = steps(&app); apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into())); assert_eq!(font_of(&app, id), "Source Serif 4", "previewed on the text"); + assert_eq!( + crate::panels::character::values(&mut app).family.as_deref(), + Some("Inter"), + "the picker must still be able to commit the previewed row" + ); apply_preview(&mut app, owner(), Preview::Shows("Source Sans 3".into())); assert_eq!(font_of(&app, id), "Source Sans 3"); apply_preview(&mut app, owner(), Preview::Ended); diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 5ccb6412a9..904de40932 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -125,6 +125,26 @@ fn home_screen(app: VectorcraftApp) -> Panel { home } +/// Home's Open while a file dialog is still open (a window the system may have placed out of sight) +/// says so in the status bar and asks for no second picker; once the first answers, Open asks again +/// (#6160). +#[test] +fn home_open_while_a_file_dialog_is_open_says_so() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let picker = crate::tests::picks::scripted(&mut app); + let mut home = home_screen(app); + home.click("Open"); + assert_eq!(picker.requests().len(), 1); + assert!(home.app().ui.status.is_empty()); + home.click("Open"); + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first"); + assert_eq!(home.app().ui.status, crate::file_asks::busy()); + picker.cancel(); + crate::file_asks::poll(&mut home.app()); + home.click("Open"); + assert_eq!(picker.requests().len(), 2, "Open asks again once the first dialog answered"); +} + /// The Home screen lists the first recent files (#663); opening one that can't be opened says so. #[test] fn home_lists_recent_files_and_a_click_opens_one() { diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 1fad419639..41b5264479 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -458,3 +458,24 @@ fn a_key_equivalent_paste_pastes_a_picture_from_another_app() { assert_eq!(images(&m), n, "press {n} pastes one picture"); } } + +/// AppKit handles a menu shortcut's key-down before winit delivers the matching key-up. +/// The two must reach the same input batch, even if this frame can have only one pass. +#[test] +fn a_native_undo_and_redo_key_equivalent_each_change_the_canvas_once() { + let mut m = Mac::new(true); + m.ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::MIN); + let id = m.app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + m.frame(vec![]); + for (chord, shift, present) in [("Cmd+Z", false, false), ("Cmd+Shift+Z", true, true)] { + let mut modifiers = if crate::keymap::platform().is_mac() { Modifiers::MAC_CMD } else { Modifiers::CTRL }; + modifiers.command = true; + modifiers.shift = shift; + m.fake.report(MenuEvent::Key(Chord::parse(chord).unwrap())); + m.frame(vec![Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: false, repeat: false, modifiers }]); + assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} with the native key-up"); + m.frame(vec![]); + assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} was applied once"); + } +} diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0c7d427a68..0b9fa40f9f 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -126,6 +126,12 @@ impl Panel { self.aim(name, target) } + /// Moves the pointer over `name` without pressing a button. + pub(crate) fn hover(&mut self, name: &str) { + let at = self.find_aimed(name).center(); + self.frame_with(vec![Event::PointerMoved(at)]); + } + /// Clicks the control named `name`. pub(crate) fn click(&mut self, name: &str) { let target = self.find_aimed(name); @@ -377,6 +383,20 @@ impl Panel { seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } + /// The named control the latest frame lays out lowest, where its name finds that control: the control a reader + /// reaches last. + pub(crate) fn lowest(&self) -> Option { + let mut names = self.names(); + names.sort(); + names.dedup(); + names + .into_iter() + .filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom()))) + .filter(|(_, bottom)| bottom.is_finite()) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(name, _)| name) + } + /// Whether the control named `name` takes input. pub(crate) fn enabled(&self, name: &str) -> bool { !self.fixture.tree().is_disabled_key(self.look(name).node) diff --git a/crates/ui-egui/src/tests/panel_scroll.rs b/crates/ui-egui/src/tests/panel_scroll.rs new file mode 100644 index 0000000000..0fbc73e271 --- /dev/null +++ b/crates/ui-egui/src/tests/panel_scroll.rs @@ -0,0 +1,61 @@ +//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262). + +use std::cell::RefCell; + +use egui::{Ui, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; + +thread_local! { + /// The panel the harness draws. + static SHOWN: RefCell = const { RefCell::new(String::new()) }; +} + +fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + let id = SHOWN.with(|s| s.borrow().clone()); + crate::dock::panel_body(app, ui, &id); +} + +/// The panels whose last control a short dock group hides and the wheel does not bring into view. +fn unreachable_panels(room_height: f32) -> Vec { + let mut stuck = Vec::new(); + for (id, _) in crate::state::all_panels() { + SHOWN.with(|s| *s.borrow_mut() = id.to_owned()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) { + panic!("file.new: {e}"); + } + // A selected path, so the panels that edit a selection show their controls. + if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) { + panic!("shape.rectangle: {e}"); + } + let mut panel = Panel::new(app, draw); + let Some(last) = panel.lowest() else { continue }; + panel.room(vec2(300.0, room_height)); + panel.frame(); + panel.frame(); + if !panel.shows(&last) || panel.in_view(&last) { + continue; + } + for _ in 0..60 { + panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0); + if panel.in_view(&last) { + break; + } + } + if !panel.in_view(&last) { + stuck.push(format!("{id}: {last:?}")); + } + } + stuck +} + +#[test] +fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() { + let mut stuck = unreachable_panels(120.0); + stuck.extend(unreachable_panels(60.0)); + assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}"); +} diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 851d438904..1d521af1c0 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -49,6 +49,10 @@ impl Picker { pub(crate) fn cancel(&self) { self.files.answer(Picked::Cancelled); } + /// The newest open pick fails with `why`, as the browser's picker does when it cannot read the file. + pub(crate) fn fail(&self, why: &str) { + self.files.answer(Picked::Failed(why.into())); + } /// The bytes a save through the service (`Files::save`) wrote to `path`. pub(crate) fn file(&self, path: &str) -> Option> { self.files.file(std::path::Path::new(path)) @@ -197,6 +201,27 @@ fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } +/// File › Open and Install Plug-in ask for no second picker while a file dialog is still open, and +/// say so; an open picker that fails says why, and opens nothing (#6160). +#[test] +fn an_open_picker_is_refused_while_a_dialog_is_open_and_a_failed_one_says_why() { + for command in ["file.open", "ui.installPlugin"] { + let mut app = app(); + let picker = scripted(&mut app); + asks(&mut app, command); + for again in ["file.open", "ui.installPlugin"] { + assert_eq!(app.run(again, json!({})), Err(file_asks::busy().to_string()), "{again} after {command}"); + } + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first after {command}"); + picker.fail("the file could not be read"); + settle(&mut app); + assert_eq!(app.ui.status, "the file could not be read", "{command}"); + assert!(app.session.documents().is_empty(), "{command}"); + asks(&mut app, command); + assert_eq!(picker.requests().len(), 2, "{command} asks again once the first answered"); + } +} + /// The picks' answers, then the rest of a frame's pumps (Save Changes goes on once its save is written). fn settle(app: &mut VectorcraftApp) { let ctx = app.ui_ctx.clone().unwrap_or_default(); diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index ff7c9e71ee..351efaec28 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -181,7 +181,9 @@ fn plugins_are_listed_in_the_object_and_effect_menus() { #[test] fn filter_dialog_previews_and_commits_one_undo_step() { - let mut h = window(app()); + let mut app = app(); + app.canvas.worker_started = true; // Canvas uploads finish within the frame being asserted. + let mut h = window(app); h.state_mut().run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(DESATURATE)})).unwrap(); let id = red_rect(h.state_mut()); let undo = h.state().session.doc().unwrap().history.undo.len(); @@ -189,12 +191,38 @@ fn filter_dialog_previews_and_commits_one_undo_step() { step(&mut h); assert!(top(h.state()).is_some(), "dialog open"); assert_eq!(fields(h.state())["amount"], json!(100.0)); + // A click in the visible slider must reach the same values the live preview reads. + use egui_kittest::kittest::Queryable as _; + // Let the modal finish its opening placement before reading a widget's screen bounds. + for _ in 0..3 { + step(&mut h); + } + let at = h.get_by_role(egui::accesskit::Role::Dialog).get_by_role(egui::accesskit::Role::Slider).rect().center(); + h.input_mut().events.push(egui::Event::PointerMoved(at)); + step(&mut h); + for pressed in [true, false] { + h.input_mut().events.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }); + step(&mut h); + } + let clicked = fields(h.state()); + assert!(clicked["amount"].as_f64().is_some_and(|amount| amount > 0.0 && amount < 100.0), "slider at {at:?}: {clicked}"); // Agents set fields like `ui.dialog.set` does; the frame previews them. set_field(&mut h, "amount", json!(50)).unwrap(); step(&mut h); assert!(h.state().session.in_interaction(), "previewing"); - let [r, g, _] = fill_rgb(h.state(), id); - assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}"); + let [r, g, b] = fill_rgb(h.state(), id); + for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] { + assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}"); + } + step(&mut h); + let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame"); + let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated(); + assert_eq!(shown_fill, fill_rgb(h.state(), id), "the canvas showed the preview before OK"); answer(&mut h, true); assert!(top(h.state()).is_none()); let st = h.state().session.doc().unwrap(); diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs new file mode 100644 index 0000000000..66799faf6d --- /dev/null +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -0,0 +1,412 @@ +//! Ctrl+wheel over the canvas with the Quick Pen tool changes the arc size and leaves the view as it +//! is; the arc size commands step it as `[` and `]` do. + +use craft::behavior::CanvasView; +use craft::ui::canvas::{ViewCommands, ViewRequest}; +use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, Pos2, TouchPhase, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::SubPath; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use super::taskbar::{Rig, on_canvas}; +use crate::VectorcraftApp; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("quickPen"); + app.run("tool.setOption", json!({"key": "action", "value": "sharpArc"})).unwrap(); + app +} + +/// The Control key as egui reports it: with Command on Windows and Linux, alone on macOS. +fn ctrl() -> Modifiers { + if crate::keymap::platform().is_mac() { Modifiers::CTRL } else { Modifiers { ctrl: true, command: true, ..Modifiers::NONE } } +} + +fn wheel(unit: MouseWheelUnit, dy: f32, phase: TouchPhase, modifiers: Modifiers, source: MouseWheelSource) -> Event { + Event::MouseWheel { unit, delta: vec2(0.0, dy), phase, modifiers, source } +} + +/// A mouse wheel's notches of `dy` lines in one event. +fn notch(dy: f32, modifiers: Modifiers) -> Event { + wheel(MouseWheelUnit::Line, dy, TouchPhase::Move, modifiers, MouseWheelSource::Wheel) +} + +/// A touchpad's motion of `dy` points. +fn pad(phase: TouchPhase, dy: f32, modifiers: Modifiers) -> Event { + wheel(MouseWheelUnit::Point, dy, phase, modifiers, MouseWheelSource::Trackpad) +} + +/// The points of a touchpad's motion that make one wheel line: on macOS a line of the canvas's +/// navigation; on Windows and Linux, where the framework reads a touchpad's Ctrl+scroll as a pinch, +/// egui's line scroll speed. +fn line(rig: &Rig) -> f32 { + if crate::keymap::platform().is_mac() { + crate::app::view::navigation(&rig.app().session.prefs).wheel_line + } else { + rig.fx.ctx().options(|o| o.input_options.line_scroll_speed) + } +} + +fn center(rig: &Rig) -> Pos2 { + rig.app().canvas_view().unwrap().rect.center() +} + +/// One frame with the pointer over `at` and `events`, then a pause past the end of a wheel turn. +fn turn_at(rig: &mut Rig, at: Pos2, events: Vec) { + rig.fx.frame(vec![Event::PointerMoved(at)]); + rig.fx.frame(events); + rig.fx.advance(1.5); + rig.fx.frame(vec![]); +} + +fn turn(rig: &mut Rig, events: Vec) { + let at = center(rig); + turn_at(rig, at, events); +} + +fn click_doc(rig: &Rig, x: f64, y: f64) { + let mut app = rig.app(); + let v = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } +} + +fn paths(app: &VectorcraftApp) -> Vec { + let mut v = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.extend(path.subpaths.iter().cloned()); + } + }); + v +} + +fn arc_size(rig: &Rig) -> f64 { + rig.app().session.tool_options()["turn"].as_f64().unwrap() +} + +fn undo_len(rig: &Rig) -> usize { + rig.app().session.active().unwrap().history.undo.len() +} + +fn view(rig: &Rig) -> CanvasView { + rig.app().canvas_view().unwrap() +} + +/// Ctrl+wheel with the Quick Pen tool: a notch up makes the last sharp-corner arc 15° larger and +/// notches down make it 15° smaller per notch, each as one undo step; the view neither zooms nor +/// scrolls. With Shift or Alt added the wheel leaves the arc size; without Ctrl it scrolls the view. +#[test] +fn ctrl_wheel_changes_the_arc_size_and_not_the_view() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + click_doc(rig, 100.0, 150.0); + click_doc(rig, 200.0, 150.0); + let drawn = paths(&rig.app())[0].clone(); + let undo = undo_len(rig); + let still = view(rig); + + turn(rig, vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_ne!(paths(&rig.app())[0], drawn, "the last arc changed"); + assert_eq!(paths(&rig.app()).len(), 1); + assert_eq!(undo_len(rig), undo + 1); + assert_eq!(view(rig), still, "Ctrl+wheel did not zoom or scroll"); + + turn(rig, vec![notch(-1.0, ctrl()), notch(-1.0, ctrl())]); + assert_eq!(arc_size(rig), 165.0, "two notches down"); + assert_eq!(undo_len(rig), undo + 3); + assert_eq!(view(rig), still); + + for modifiers in [Modifiers { shift: true, ..ctrl() }, Modifiers { alt: true, ..ctrl() }] { + turn(rig, vec![notch(1.0, modifiers)]); + assert_eq!(arc_size(rig), 165.0, "{modifiers:?}"); + } + + let still = view(rig); + turn(rig, vec![notch(1.0, Modifiers::NONE)]); + assert_eq!(arc_size(rig), 165.0, "a plain wheel"); + assert_ne!(view(rig), still, "a plain wheel scrolls the view"); + }); +} + +/// The first claimed share keeps both the stored view and the tool host's document point. +#[test] +fn the_first_ctrl_wheel_frame_keeps_the_view_and_pointer() { + let mut app = app(); + app.ui.view.rulers = true; + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let at = center(rig) + vec2(80.0, 40.0); + rig.fx.frame(vec![Event::PointerMoved(at)]); + let still = view(rig); + let point = rig.app().hover_doc.expect("the pointer is over the canvas"); + let win = crate::doc_windows::current(&rig.app()).unwrap(); + let id = crate::canvas::canvas_id(win); + let shown = craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view; + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(view(rig).zoom, still.zoom, "the first share keeps the zoom"); + assert_eq!(view(rig).center, still.center, "the first share keeps the pan"); + assert_eq!(view(rig).rect, still.rect, "the content stays inside the rulers"); + assert_eq!(craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view, shown, "the tool host sees the saved view"); + assert_eq!(rig.app().hover_doc, Some(point), "the tool host uses the saved view in the same frame"); + }); +} + +#[test] +fn a_queued_fit_survives_the_first_ctrl_wheel_frame() { + let mut app = app(); + app.session.prefs.animated_zoom = false; + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let fitted = view(rig); + rig.app().run("view.zoomIn", json!({})).unwrap(); + rig.fx.settle(); + assert_ne!(view(rig).zoom, fitted.zoom); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.app().request_view(ViewRequest::Command(ViewCommands::FitArtboard), None); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(view(rig), fitted, "the queued fit reaches the stored view in the same frame"); + }); +} + +#[test] +fn the_toolbar_keeps_its_anchor_on_the_first_ctrl_wheel_frame() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + click_doc(rig, 100.0, 150.0); + rig.fx.settle(); + let bar = rig.target("Quick Pen").unwrap().rect; + rig.fx.frame(vec![Event::PointerMoved(center(rig) + vec2(-120.0, -80.0))]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(rig.target("Quick Pen").unwrap().rect, bar, "the toolbar maps its anchor through the saved space"); + }); +} + +#[test] +fn a_claimed_wheel_makes_no_step_outside_the_content() { + let mut app = app(); + app.ui.view.rulers = true; + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + let still = view(rig); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + let outside = egui::pos2(still.rect.left() - 1.0, still.rect.center().y); + rig.fx.frame(vec![Event::PointerMoved(outside)]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "a share over a ruler makes no step"); + assert_eq!(view(rig), still, "the claimed gesture still keeps the view"); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 210.0, "the gesture resumes inside the content"); + }); +} + +#[test] +fn a_native_pinch_with_control_zooms_the_view() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.hold(ctrl()); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + let still = view(rig); + rig.fx.frame(vec![Event::Zoom(1.25)]); + assert!(view(rig).zoom > still.zoom, "a native pinch keeps its zoom"); + assert_eq!(arc_size(rig), 180.0); + let zoomed = view(rig); + rig.fx.frame(vec![Event::Zoom(1.25)]); + assert!(view(rig).zoom > zoomed.zoom, "the pinch was not claimed as an arc gesture"); + rig.fx.hold(Modifiers::NONE); + }); +} + +/// Opposite notches in one frame use the framework's net lines and keep the tool host's view. +#[test] +fn opposite_notches_use_the_frameworks_reported_net_motion() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.frame(vec![Event::PointerMoved(center(rig) + vec2(80.0, 40.0))]); + let win = crate::doc_windows::current(&rig.app()).unwrap(); + let id = crate::canvas::canvas_id(win); + let shown = craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view; + for (start, notches, expected) in + [(345, vec![1.0, -1.0], 345.0), (345, vec![1.0, 1.0, -1.0], 345.0), (180, vec![1.0, -1.0], 180.0), (180, vec![1.0, 1.0, -1.0], 195.0)] + { + rig.app().run("tool.setOption", json!({"key": "turn", "value": start})).unwrap(); + rig.fx.frame(notches.into_iter().map(|dy| notch(dy, ctrl())).collect()); + assert_eq!(arc_size(rig), expected, "the framework reports net lines, including at the arc limit"); + assert_eq!(craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view, shown, "mixed notches keep the tool host's view"); + rig.fx.advance(1.5); + rig.fx.frame(vec![]); + } + }); +} + +/// A touchpad steps once per wheel line of motion: half a line makes no step, the second half of the +/// same gesture makes one, and momentum after it makes none (egui reports momentum on macOS). Half a +/// line in a later turn does not add to the half before it. +#[test] +fn a_touchpad_steps_once_per_wheel_line() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let line = line(rig); + let still = view(rig); + rig.fx.hold(ctrl()); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.fx.frame(vec![pad(TouchPhase::Start, 0.0, ctrl())]); + rig.fx.frame(vec![pad(TouchPhase::Move, line / 2.0, ctrl())]); + assert_eq!(arc_size(rig), 180.0, "half a line"); + rig.fx.frame(vec![pad(TouchPhase::Move, line / 2.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "a whole line"); + rig.fx.frame(vec![pad(TouchPhase::End, 0.0, ctrl())]); + if crate::keymap::platform().is_mac() { + rig.fx.frame(vec![wheel(MouseWheelUnit::Point, 3.0 * line, TouchPhase::Move, ctrl(), MouseWheelSource::Momentum)]); + assert_eq!(arc_size(rig), 195.0, "momentum makes no step"); + } + assert_eq!(view(rig), still, "the view stays"); + + rig.fx.advance(2.0); + turn(rig, vec![pad(TouchPhase::Move, line / 2.0, ctrl())]); + turn(rig, vec![pad(TouchPhase::Move, line / 2.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "two turns of half a line each"); + rig.fx.hold(Modifiers::NONE); + }); +} + +/// Shift pressed and let go between two wheel events of a touchpad gesture held with Ctrl counts for +/// the rest of the gesture; Ctrl let go during the gesture still counts until it ends. egui reports a +/// touchpad gesture's phases on macOS; on Windows and Linux the framework reads a touchpad's +/// Ctrl+scroll as a pinch, which carries no phases. +// test-lint: allow never-run touchpad gesture phases reach the app only on macOS +#[cfg(target_os = "macos")] +#[test] +// test-lint: allow never-run egui reports touchpad gesture phases only on macOS +fn keys_held_during_a_touchpad_gesture_count_until_it_ends() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let line = line(rig); + let both = Modifiers { shift: true, ..ctrl() }; + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.fx.frame(vec![pad(TouchPhase::Start, 0.0, ctrl())]); + rig.fx.frame(vec![pad(TouchPhase::Move, line, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "a line up with Ctrl"); + rig.fx.frame(vec![pad(TouchPhase::Move, line, Modifiers::NONE)]); + assert_eq!(arc_size(rig), 210.0, "Ctrl let go still counts"); + rig.fx.frame(vec![Event::ModifiersChanged(both), Event::ModifiersChanged(ctrl())]); + rig.fx.frame(vec![pad(TouchPhase::Move, line, ctrl())]); + assert_eq!(arc_size(rig), 210.0, "Shift tapped mid-gesture"); + rig.fx.frame(vec![pad(TouchPhase::End, 0.0, ctrl())]); + }); +} + +/// Ctrl+wheel over the Quick Pen toolbar, under a modal window, and for the rest of a turn begun +/// under one, leaves the arc size. +#[test] +fn ctrl_wheel_over_the_toolbar_or_under_a_dialog_makes_no_step() { + let mut app = app(); + on_canvas(&mut app, |rig| { + let bar = rig.target("Quick Pen").expect("the toolbar shows").rect; + turn_at(rig, bar.center(), vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 180.0, "over the toolbar"); + + rig.app().run("edit.preferences", json!({})).unwrap(); + rig.fx.settle(); + let at = center(rig); + rig.fx.frame(vec![Event::PointerMoved(at)]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 180.0, "under the dialog"); + rig.app().prefs = None; + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 180.0, "the rest of a turn begun under the dialog"); + rig.fx.advance(1.5); + turn(rig, vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "a new turn"); + }); +} + +/// With another tool, Ctrl+wheel leaves the Quick Pen's arc size and moves the view as before. +#[test] +fn ctrl_wheel_with_another_tool_moves_the_view() { + let mut app = app(); + app.select_tool("pen"); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let still = view(rig); + turn(rig, vec![notch(1.0, ctrl())]); + assert_eq!(rig.app().session.tool_options_of("quickPen")["turn"], json!(180.0)); + assert_ne!(view(rig), still); + }); +} + +/// The arc size commands step the size by 15° within 1° to 359°, return false at the ends and with +/// another tool, and change the last sharp-corner arc of the path being drawn, also while a press +/// drags it. +#[test] +fn the_arc_size_commands_step_within_the_range() { + let mut app = app(); + let arc = |app: &VectorcraftApp| app.session.tool_options()["turn"].as_f64().unwrap(); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(arc(&app), 195.0); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(true)); + for _ in 0..10 { + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + } + assert_eq!(arc(&app), 330.0); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(false), "360° is past 359°"); + assert_eq!(arc(&app), 345.0); + + let v = vectorcraft_engine::ViewInfo { smart_guides: false, ..Default::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, 100.0, 150.0), v).unwrap(); + } + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, 200.0, 150.0), v).unwrap(); + } + let drawn = paths(&app)[0].clone(); + let undo = app.session.active().unwrap().history.undo.len(); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(true)); + assert_ne!(paths(&app)[0], drawn); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + + // During a drag the arc being dragged takes the new size and the drag goes on; the piece and its + // size change are one undo step. + app.run("tool.setOption", json!({"key": "turn", "value": 180})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 260.0, 150.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 150.0), v).unwrap(); + assert!(app.session.tool_busy(), "the press drags"); + let dragged = paths(&app)[0].clone(); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(arc(&app), 195.0); + assert!(app.session.tool_busy(), "the drag goes on"); + assert_ne!(paths(&app)[0], dragged, "the arc being dragged is drawn again with the new size"); + // The tool's size set ahead of the dragged arc's: a step that brings the arc to it still reports + // the change. + app.run("tool.setOption", json!({"key": "turn", "value": 210})).unwrap(); + let sized = paths(&app)[0].clone(); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(arc(&app), 210.0); + assert_ne!(paths(&app)[0], sized); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 150.0), v).unwrap(); + assert!(!app.session.tool_busy()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the piece and its size changes are one undo step"); + + app.select_tool("pen"); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.tool_options_of("quickPen")["turn"], json!(210.0)); +} diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs new file mode 100644 index 0000000000..46c6ccc867 --- /dev/null +++ b/crates/ui-egui/src/tests/script_print.rs @@ -0,0 +1,343 @@ +//! A script's jobs for a printer (`Document.print` without a file): the run lists the print +//! service's printers, and its jobs are sent after it ends, only when the person at the keyboard +//! approves them with a click on Print. + +use std::cell::RefCell; +use std::rc::Rc; + +use craft::ui::dialog::DialogResult; +use egui::{Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::script_dialogs::{cancel, confirm, fields, is_open, pump, set}; +use crate::dialogs::script_run::{self, PRINT_BY_PERSON, PRINT_ENABLE_DELAY_SECS, PRINT_KIND, PRINTS_DROPPED, PrintAnswer, ScriptPrint}; +use crate::print::{PrintJob, PrintService, Printer}; +use crate::{Services, VectorcraftApp, menus, script_runs}; + +/// What the service was sent: (printer, title, bytes). +type Sent = Rc, String, Vec)>>>; + +/// A print service that records the jobs it is sent, with the printers `names` (the first one the +/// default), which lets scripts print when `scripts` is true. +struct Spool { + sent: Sent, + names: Rc>>, + scripts: bool, +} + +impl PrintService for Spool { + fn printers(&mut self) -> Vec { + self.names.borrow().iter().enumerate().map(|(i, name)| Printer::new(name.clone()).is_default(i == 0)).collect() + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec())); + Ok(format!("Sent to {}", job.printer.unwrap_or("the default printer"))) + } + + fn scripts_may_print(&self) -> bool { + self.scripts + } +} + +/// An app in a window, with a document, a print service listing Office (the default) and Lab, and +/// no warning before a script runs. +fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc>>) { + let sent = Sent::default(); + let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()])); + let spool = Spool { sent: sent.clone(), names: names.clone(), scripts }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() })); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + (app, sent, names) +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +/// Runs `source` as File › Scripts › Other Script… runs it, to its end. +fn run(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({ "source": source, "name": "p.js" })).unwrap().unwrap(); + for _ in 0..10_000 { + script_runs::poll(app); + if !app.session.script_running() { + return; + } + } + panic!("the script did not end"); +} + +const PRINT_TO_LAB: &str = + "var o = new PrintOptions(); o.printerName = 'Lab'; app.activeDocument.print(o); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"; + +fn asking(app: &VectorcraftApp) -> bool { + is_open::(app) +} + +/// One pass of the dialog host at `time` with `events`, then the frame's pump → the texts drawn, +/// with where. +fn frame(app: &mut VectorcraftApp, time: f64, events: Vec) -> Vec<(String, Rect)> { + fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| dialogs.with(|host| host.run(ui))); + out.textures_delta.clear(); + pump(app); + let mut v = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + v +} + +/// Where the button `label` was drawn: the last text that reads it (the heading reads Print too). +fn button(texts: &[(String, Rect)], label: &str) -> Pos2 { + texts.iter().rev().find(|(t, _)| t.trim() == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1.center() +} + +/// A click of the primary button at `pos` from `time`: hover, press and release in frames of their +/// own, as a person's click comes. +fn click(app: &mut VectorcraftApp, time: f64, pos: Pos2) { + let press = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for (i, event) in [egui::Event::PointerMoved(pos), press(true), press(false)].into_iter().enumerate() { + frame(app, time + 0.01 * i as f64, vec![event]); + } +} + +/// A press of `key` with no modifiers at `time`, let go in a frame of its own, as a person lets go +/// of it. +fn key(app: &mut VectorcraftApp, time: f64, key: egui::Key) { + let event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(app, time, vec![event(true)]); + frame(app, time + 0.01, vec![event(false)]); +} + +/// Draws the open question from `time` until it settles, then clicks its `label` button once +/// [`PRINT_ENABLE_DELAY_SECS`] have passed since it was first drawn. +fn click_after_delay(app: &mut VectorcraftApp, time: f64, label: &str) { + frame(app, time, vec![]); + frame(app, time + 0.1, vec![]); + let later = time + PRINT_ENABLE_DELAY_SECS + 0.1; + let pos = button(&frame(app, later, vec![]), label); + click(app, later + 0.1, pos); +} + +/// The job is sent after the run's changes are kept, once, and only when the person at the +/// keyboard clicks Print: Print from automation is refused and the question opens again, and +/// `ui.dialog.set` and `ui.dialog.confirm` cannot print. +#[test] +fn a_scripts_print_job_is_sent_only_when_the_person_clicks_print() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + assert_eq!(objects(&app), 1, "the run's changes are kept"); + assert!(asking(&app)); + assert!(sent.borrow().is_empty(), "nothing is sent before the person answers"); + let jobs = fields(&app, PRINT_KIND)["jobs"].clone(); + assert_eq!(jobs[0]["printer"], "Lab"); + assert_eq!(jobs.as_array().map(Vec::len), Some(1)); + for (field, value) in [("jobs", json!([])), ("printer", json!("Office"))] { + let e = set(&app, PRINT_KIND, field, value).unwrap_err(); + assert!(e.contains(&format!("unknown field `{field}`")), "{field}: {e}"); + } + assert_eq!(set(&app, PRINT_KIND, "answer", json!("print")).unwrap_err(), PRINT_BY_PERSON); + assert!(!confirm(&mut app, PRINT_KIND), "confirm takes only Cancel"); + assert!(asking(&app), "the question stays open"); + // A Print that a pass automation drove gave. + script_run::with_host(&app, |host, ctx| host.cancel::(ctx)).unwrap(); + let _ = script_run::with_host(&app, |host, _| host.take::()); + app.ui.answering_control = true; + script_run::settle_print(&mut app, DialogResult::Ok(PrintAnswer { print: true })); + app.ui.answering_control = false; + assert_eq!(app.ui.status, PRINT_BY_PERSON); + assert!(asking(&app), "the question opens again"); + assert!(sent.borrow().is_empty()); + click_after_delay(&mut app, 10.0, "Print"); + assert!(!asking(&app)); + { + let sent = sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0.as_deref(), Some("Lab")); + assert!(sent[0].2.starts_with(b"%PDF")); + } + assert_eq!(app.ui.status, "Sent to Lab"); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert_eq!(sent.borrow().len(), 1, "a job is sent once"); + assert!(!asking(&app)); +} + +/// Enter does not print, and Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the +/// question was first drawn; a click after that prints. +#[test] +fn enter_or_an_early_click_does_not_print() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + frame(&mut app, 10.0, vec![]); + frame(&mut app, 10.05, vec![]); + let pos = button(&frame(&mut app, 10.1, vec![]), "Print"); + click(&mut app, 10.2, pos); + assert!(asking(&app), "an early click"); + for time in [10.3, 10.4] { + key(&mut app, time, egui::Key::Enter); + assert!(asking(&app), "at {time}"); + } + let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; + for time in [later, later + 0.1] { + key(&mut app, time, egui::Key::Enter); + assert!(asking(&app), "Enter at {time}"); + } + // Tab gives a button the keyboard focus: Enter on it does not print either. + key(&mut app, later + 0.15, egui::Key::Tab); + key(&mut app, later + 0.17, egui::Key::Enter); + assert!(asking(&app), "Enter on the focused button"); + // Nor does an Enter pressed and let go within one frame. + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&mut app, later + 0.185, vec![enter(true), enter(false)]); + assert!(asking(&app), "Enter pressed and let go in one frame"); + assert!(sent.borrow().is_empty(), "nothing is sent"); + // The question has settled where it stays; Print is clicked there. + let pos = button(&frame(&mut app, later + 0.19, vec![]), "Print"); + click(&mut app, later + 0.2, pos); + assert!(!asking(&app)); + assert_eq!(sent.borrow().len(), 1); +} + +/// While a text field has the keyboard when the run ends, the question waits, and nothing is sent; +/// it opens at the first poll after the field lets the keyboard go. +#[test] +fn the_print_question_waits_while_a_text_field_has_the_keyboard() { + let (mut app, sent, _) = print_app(true); + let ctx = app.ui_ctx.clone().unwrap(); + let id = egui::Id::unique("script-print-typing"); + let mut text = String::new(); + let mut draw = |time: f64, focus: bool| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(id)); + if focus { + r.request_focus(); + } + }); + out.textures_delta.clear(); + }; + draw(1.0, true); + draw(1.1, false); + assert!(ctx.text_edit_focused()); + run(&mut app, PRINT_TO_LAB); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert!(!asking(&app), "the question waits"); + assert!(app.session.script_prints_waiting(), "the job waits"); + ctx.memory_mut(|m| m.surrender_focus(id)); + script_runs::poll(&mut app); + assert!(asking(&app)); + assert!(sent.borrow().is_empty()); +} + +/// Cancel, from anyone, drops the jobs and keeps the run's changes. +#[test] +fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { + let (mut app, sent, _) = print_app(true); + run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}")); + assert_eq!(app.session.script_prints().len(), 2); + cancel(&mut app, PRINT_KIND); + assert!(!asking(&app)); + assert!(!app.session.script_prints_waiting()); + assert_eq!(app.ui.status, PRINTS_DROPPED); + script_runs::poll(&mut app); + assert!(!asking(&app), "the question does not come back"); + assert!(sent.borrow().is_empty()); + assert_eq!(objects(&app), 1); + // `answer: "cancel"` with `ui.dialog.confirm` does the same. + run(&mut app, PRINT_TO_LAB); + set(&app, PRINT_KIND, "answer", json!("cancel")).unwrap(); + assert!(confirm(&mut app, PRINT_KIND)); + assert!(!asking(&app)); + assert!(!app.session.script_prints_waiting()); + // The Cancel button, at once or later, does the same. + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + frame(&mut app, 10.0, vec![]); + let pos = button(&frame(&mut app, 10.1, vec![]), "Cancel"); + click(&mut app, 10.2, pos); + assert!(!asking(&app)); + assert!(!app.session.script_prints_waiting()); + assert_eq!(app.ui.status, PRINTS_DROPPED); + // The app draws on: the closed question's layer is gone by the next frame. + frame(&mut app, 10.3, vec![]); + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + click_after_delay(&mut app, 20.0, "Cancel"); + assert!(!asking(&app)); + assert!(!app.session.script_prints_waiting()); + assert!(sent.borrow().is_empty()); + assert_eq!(objects(&app), 4); +} + +/// A run that fails asks nothing and sends nothing; a printer that went away before Print is +/// refused and no job is sent. +#[test] +fn a_failed_run_or_a_printer_that_went_away_sends_nothing() { + let (mut app, sent, names) = print_app(true); + run(&mut app, &format!("{PRINT_TO_LAB} throw new Error('late');")); + assert!(!asking(&app)); + assert!(!app.session.script_prints_waiting()); + assert_eq!(objects(&app), 0); + run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}")); + assert!(asking(&app)); + names.borrow_mut().retain(|n| n != "Lab"); + click_after_delay(&mut app, 10.0, "Print"); + assert_eq!(app.ui.status, "The printer Lab is no longer installed: the script's print jobs were not sent"); + assert!(sent.borrow().is_empty(), "neither job is sent"); + assert!(!asking(&app)); +} + +/// Without a service that lets scripts print (the web's), or without any, printing to a printer +/// from a script throws and nothing is asked or sent. +#[test] +fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() { + let (mut app, sent, _) = print_app(false); + run(&mut app, PRINT_TO_LAB); + assert!(app.ui.status.contains("Printing to a printer is not available here"), "{}", app.ui.status); + assert!(!asking(&app)); + assert!(sent.borrow().is_empty()); + let mut bare = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + bare.run("file.new", json!({})).unwrap(); + bare.session.prefs.show_external_script_warning = false; + run(&mut bare, "vc.log(app.printerList.length);"); + assert!(bare.ui.status.contains("Application.printerList is not available here"), "{}", bare.ui.status); + // A run the app started lists the service's printers; a later run without one does not. + let (mut app, _, _) = print_app(true); + run(&mut app, "var l = app.printerList; vc.log([l.length, l[0].name, l[1].name]);"); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "Office", "Lab"]])); + assert!(app.session.script_printers.is_none()); + // A run that does not start leaves no list behind for a later one. + assert!(app.run("script.run", json!({"source": "1", "path": "x.js"})).is_err()); + assert!(app.session.script_printers.is_none()); +} + +/// Space on Print, once Tab gave it the keyboard focus after [`PRINT_ENABLE_DELAY_SECS`], prints: +/// a keyboard user can approve the jobs without a mouse. +#[test] +fn space_on_the_focused_print_button_prints() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + frame(&mut app, 10.0, vec![]); + let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; + frame(&mut app, later, vec![]); + key(&mut app, later + 0.1, egui::Key::Tab); + key(&mut app, later + 0.2, egui::Key::Space); + assert!(!asking(&app)); + assert_eq!(sent.borrow().len(), 1); +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 374fe2b460..09b5eec0b0 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -218,13 +218,16 @@ pub fn mono(size: f32) -> FontId { mod tests { use super::*; - /// The saved strings are what Preferences and old settings files hold. + /// Preferences saves a brightness by its id, and old settings files hold its label, in any + /// case; any other text is not a brightness. #[test] - fn brightness_roundtrip() { - for b in Brightness::ALL { - assert_eq!(Brightness::parse(b.id()), Some(b)); - assert_eq!(Brightness::parse(b.label()), Some(b)); - } + fn brightness_reads_saved_ids_and_old_labels() { + assert_eq!(Brightness::MediumDark.id(), "mediumDark", "the id Preferences saves"); + assert_eq!(Brightness::parse("mediumDark"), Some(Brightness::MediumDark)); + assert_eq!(Brightness::parse("Medium Light"), Some(Brightness::MediumLight)); + assert_eq!(Brightness::parse("LIGHT"), Some(Brightness::Light)); + assert_eq!(Brightness::parse("medium"), None); + assert_eq!(Brightness::parse(""), None); } /// A size `app_sizes` cannot read is only logged and dropped, which brings the pill buttons back unnoticed. diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index e9898a078f..5e7c48758c 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -214,7 +214,7 @@ mod tests { #[test] fn jobs_come_back_newest_last_per_slot() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; for k in 1..=3 { assert!(w.submit(0, k, job(k))); @@ -238,7 +238,7 @@ mod tests { #[test] fn discarded_jobs_do_not_run_and_the_running_one_finishes() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; // A job that holds the thread until it is let go, so the others queue behind it. let (started, running) = channel::<()>(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e80ed26a77..34a7829ba9 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -2,8 +2,8 @@ //! Draw, Modify, Type, Navigate, Color). Window → Toolbars → Advanced shows every tool group; the //! double arrow at the top (or Window → Toolbars → Double Column, `window.toolbarColumns`) lays the //! tools out in one or two columns. -//! Bottom: fill/stroke proxy, colour/gradient/none, drawing modes, screen mode; the rail's own Edit -//! Toolbar button opens the All Tools drawer (`edit_toolbar`). +//! Bottom: fill/stroke proxy, colour/gradient/none, drawing modes, screen mode, Search and Edit +//! Toolbar. Edit opens the native All Tools drawer (`edit_toolbar`). //! //! The dock draws the rail ([`rail_view`]) for the Tools panel, for each toolbar made with New //! Toolbar and for each group torn off either of them (a `strip:` panel). @@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC use craft::ui::display::Divider; use craft::ui::docking::{DockGrid, GroupAt}; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::pickers::{Anchor9, ReferencePointLook, Select}; use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot}; use craft::ui::runtime::commands::{self, CommandRef}; @@ -263,12 +263,13 @@ fn strip_tools(app: &VectorcraftApp, parent: &Owner, first: &str) -> Vec<&'stati groups_of(app, parent).into_iter().find(|g| g.first().is_some_and(|f| *f == first)).unwrap_or_default() } -/// The dock grid of the rail panel `owner`: a cell for each of its slots and its Edit Toolbar button. Its rail draws at -/// the chrome's density, so the dock resolves the grid's steps in its own. +/// The dock grid of the rail panel `owner`: a cell for each tool slot and a custom toolbar's Edit Toolbar button. +/// The Tools panel keeps its actions in the host footer. The rail draws at the chrome's density. pub(crate) fn dock_grid(app: &VectorcraftApp, owner: &Owner) -> DockGrid { let cells = match owner { Owner::Strip(parent, first) => strip_tools(app, parent, first).len(), - _ => groups_of(app, owner).len() + 1, + Owner::Tools => groups_of(app, owner).len(), + Owner::Toolbar(_) => groups_of(app, owner).len() + 1, }; DockGrid::rail(cells).density(rail_density(app, owner)) } @@ -461,7 +462,10 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m rail = rail.footer_scrolls(); } if own_bar { - rail = rail.tear_off().edit_toolbar(tl!("Edit Toolbar")); + rail = rail.tear_off(); + if !tools_panel { + rail = rail.edit_toolbar(tl!("Edit Toolbar")); + } } if editing(app, &owner) { rail = rail.editing(); @@ -471,9 +475,11 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m _ => None, }; let measured = matches!(at, GroupAt::Measure(_)); + let mut tools_edit = None; let footer = |ui: &mut Ui, footer: RailFooter| { if tools_panel { bottom_controls(app, ui, footer); + tools_edit = search_and_edit_buttons(app, ui, footer); } else if let Some(id) = bar { crate::custom_toolbars::add_menu(app, ui, id, footer, measured); } @@ -482,7 +488,11 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m GroupAt::Measure(width) => return rail.measure_rail(ui, width, footer).y, GroupAt::Show(rect) => rect, }; - let out = rail.show_rail(ui, footer); + let mut out = rail.show_rail(ui, footer); + if tools_panel { + // The native footer opener follows the same drawer, focus and customization path. + out.edit_toolbar = tools_edit; + } if let Some(tool) = out.select.as_deref().filter(|tool| *tool != app.session.tool_id()) { // Not an error to report: a tool the command refuses stays unselected. app.run("tool.select", json!({ "tool": tool })).ok(); @@ -883,5 +893,33 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod card; +/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last. +fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option { + let enabled = !crate::panel_docking::modal_window_up(app); + let mut edit = None; + let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| { + IconButton::command(IconId::new("search"), "help.commandPalette") + .label(tl!("Search commands")) + .tooltip(tl!("Search commands, tools, panels and effects")) + .selected(app.ui.palette_open) + .enabled(enabled) + .show(ui); + edit = Some( + IconButton::new(IconId::new("more")) + .label(tl!("Edit Toolbar")) + .selected(editing(app, &Owner::Tools)) + .enabled(crate::menus::enabled(app, "window.editToolbar")) + .show(ui) + .response, + ); + }; + if footer.columns > 1 { + Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); + } else { + Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); + } + edit +} + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 9d8040e68f..91becce66b 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -318,6 +318,9 @@ fn the_controls_under_the_tools_share_a_line_under_a_rule() { let chips = ["Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)"].map(|label| named_rect(&nodes, label)); assert!(chips.iter().all(|r| (r.top() - chips[0].top()).abs() < 0.5), "one line: {chips:?}"); let last = cells(&app, &nodes).into_iter().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).expect("the rail shows tools"); + // The line fits the column of tools, and the chips do not cover each other. + assert!(chips.iter().all(|r| r.left() >= last.left() - 0.5 && r.right() <= last.right() + 0.5), "inside {last:?}: {chips:?}"); + assert!(chips.windows(2).all(|w| w[0].right() <= w[1].left() + 0.01), "apart: {chips:?}"); let proxy = named_rect(&nodes, "Fill and Stroke"); let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 2000.0))); let out = crate::testing::app_frame(&mut app, &ctx, egui::RawInput { time: Some(1.0), screen_rect, ..Default::default() }); @@ -336,6 +339,22 @@ fn the_controls_under_the_tools_share_a_line_under_a_rule() { assert_eq!(rules, 1, "one rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}"); } +/// At UI scale 2 the one-column rail's Color, Gradient and None chips still share one line inside the column of tools. +#[test] +fn the_color_chips_share_a_line_at_ui_scale_2() { + let mut app = app_with(200, 200); + let ctx = reader(); + app.session.prefs.ui_scaling = 2.0; + app.run("window.toolbarColumns", json!({ "double": false })).unwrap(); + let nodes = settled(&mut app, &ctx, 0.0, 2000.0); + assert_eq!(ctx.zoom_factor(), 2.0, "the frames run at UI scale 2"); + let chips = ["Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)"].map(|label| named_rect(&nodes, label)); + assert!(chips.iter().all(|r| (r.top() - chips[0].top()).abs() < 0.5), "one line: {chips:?}"); + let last = cells(&app, &nodes).into_iter().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).expect("the rail shows tools"); + assert!(chips.iter().all(|r| r.left() >= last.left() - 0.5 && r.right() <= last.right() + 0.5), "inside {last:?}: {chips:?}"); + assert!(chips.windows(2).all(|w| w[0].right() <= w[1].left() + 0.01), "apart: {chips:?}"); +} + /// A screen reader reads the drawing-mode buttons' state as the rail shows it, in every mode: in two columns the /// current mode's button reads pressed and the other two not pressed; in one column the single button is named for the /// current mode and cycles the modes, so it reads as a plain button with no pressed state. @@ -579,6 +598,195 @@ fn the_rail_builds_its_slots_only_when_its_tool_groups_change() { assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots"); } +/// The real Tools dock column; distinguishes its footer Search from the app bar's Search. +fn review_8758_panel(app: &VectorcraftApp, ctx: &egui::Context) -> egui::Rect { + let report = crate::panel_docking::inspect(app, ctx); + let columns = report["columns"].as_array().expect("dock columns"); + let r = &columns.iter().find(|column| column["panel"] == "tools").expect("the Tools column")["rect"]; + egui::Rect::from_min_size( + egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), + egui::vec2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), + ) +} + +fn review_8758_button<'a>(app: &VectorcraftApp, ctx: &egui::Context, nodes: &'a [Node], label: &str) -> &'a Node { + let panel = review_8758_panel(app, ctx); + nodes + .iter() + .find(|n| n.role() == Role::Button && n.label() == Some(label) && bounds(n).is_some_and(|r| panel.contains_rect(r))) + .unwrap_or_else(|| panic!("Tools footer button {label:?} is drawn")) +} + +fn review_8758_query(nodes: &[Node]) -> &str { + nodes + .iter() + .find(|n| n.role() == Role::TextInput && n.label() == Some("Search commands")) + .and_then(Node::value) + .expect("the native palette's query field") +} + +fn review_8758_unchanged_content(app: &VectorcraftApp) -> Value { + let st = app.session.active().unwrap(); + json!({"document": &*st.doc, "selection": format!("{:?}", st.selection), + "undo": st.history.undo.len(), "redo": st.history.redo.len(), "slots": slots(app)}) +} + +/// Paint the native tooltip over whole app frames, keeping the same window and dock measurements. +fn review_8758_hovered_texts(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2) -> Vec { + fn texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let mut shown = vec![]; + for i in 0..20 { + let events = match i { + 0 => vec![Event::PointerGone], + 1 => vec![Event::PointerMoved(at)], + _ => vec![], + }; + let out = crate::testing::app_frame( + app, + ctx, + egui::RawInput { + time: Some(t0 + f64::from(i) * 0.1), + events, + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 1400.0))), + ..Default::default() + }, + ); + out.shapes.iter().for_each(|shape| texts(&shape.shape, &mut shown)); + } + shown +} + +fn review_8758_edit_control(app: &mut VectorcraftApp, ctx: &egui::Context, nodes: &[Node]) { + let edit = bounds(review_8758_button(app, ctx, nodes, "Edit Toolbar")).unwrap(); + let panel = review_8758_panel(app, ctx); + let before = slots(app); + let nodes = click(app, ctx, 1.0, edit.center(), 1400.0); + assert!(app.ui.tools_drawer && app.ui.drawer_toolbar.is_none(), "Edit opens the Tools customization drawer"); + let drawer = nodes + .iter() + .find(|n| n.role() == Role::Dialog && n.label() == Some("Edit Toolbar")) + .and_then(bounds) + .expect("the native customization drawer is drawn"); + // Main anchors its native drawer to the rail's canvas side; the footer button remains its focus opener. + assert!( + drawer.left() >= panel.right() - 1.0 && drawer.top() < panel.bottom() && drawer.bottom() > panel.top(), + "the customization drawer remains beside its Tools rail: {drawer:?}, {panel:?}" + ); + assert!(nodes.iter().any(|n| n.label() == Some("All Tools")), "the customization list is present"); + assert_eq!(slots(app), before, "opening customization does not change tool membership"); + assert!(before.iter().any(|(_, tools)| tools.contains(&"rectangle"))); + app.run("toolbar.removeTool", json!({"tool": "rectangle"})).unwrap(); + assert!(!slots(app).iter().any(|(_, tools)| tools.contains(&"rectangle")), "customization still edits the toolbar"); + // Use the native close control, which returns focus to this footer's Edit button. + let close = named_rect(&nodes, "Close"); + click(app, ctx, 2.0, close.center(), 1400.0); + assert!(!app.ui.tools_drawer); + let key = |pressed| Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, 2.2, vec![key(true), key(false)], 1400.0); + settled(app, ctx, 2.3, 1400.0); + assert!(app.ui.tools_drawer, "focus returns to Edit: Enter reopens its customization drawer"); + app.run("window.editToolbar", json!({})).unwrap(); + settled(app, ctx, 2.6, 1400.0); +} + +fn review_8758_layout(double: bool) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + app.run("window.toolbarColumns", json!({"double": double})).unwrap(); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1400.0); + review_8758_edit_control(&mut app, &ctx, &nodes); + let nodes = settled(&mut app, &ctx, 3.0, 1400.0); + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); + let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); + let panel = review_8758_panel(&app, &ctx); + assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel"); + assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window"); + if double { + assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); + } else { + assert!( + search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01, + "one column keeps both controls in a fitted stack" + ); + } + let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut"); + let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform()); + let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center()); + assert!(tips.iter().any(|tip| tip == &expected), "the native Search tooltip includes its command shortcut: {tips:?}"); + let before = review_8758_unchanged_content(&app); + let tool = app.session.tool_id().to_string(); + click(&mut app, &ctx, 8.0, search.center(), 1400.0); + let nodes = frame(&mut app, &ctx, 9.0, vec![Event::Text("old query".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "old query", "the opened native search has keyboard focus"); + app.run("help.commandPalette", json!({})).unwrap(); + settled(&mut app, &ctx, 10.0, 1400.0); + let nodes = click(&mut app, &ctx, 11.0, search.center(), 1400.0); + assert!(app.ui.palette_open, "the actual footer button opens the existing command palette"); + assert!(review_8758_query(&nodes).is_empty(), "the native palette opens with a fresh query"); + let nodes = frame(&mut app, &ctx, 12.0, vec![Event::Text("focused".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "focused", "reopening gives the search field keyboard focus"); + assert!(!app.ui.tools_drawer, "Search is distinct from Edit Toolbar"); + assert_eq!(review_8758_unchanged_content(&app), before, "Search changes no document, history, selection or toolbar membership"); + assert_eq!(app.session.tool_id(), tool); +} + +#[test] +fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette() { + for double in [true, false] { + review_8758_layout(double); + } +} + +#[test] +fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1400.0); + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); + let before = review_8758_unchanged_content(&app); + click(&mut app, &ctx, 0.2, search.center(), 1400.0); + assert!(app.ui.palette_open); + let nodes = frame(&mut app, &ctx, 0.4, vec![Event::Text("Scissors".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "Scissors", "the actual focused query field receives typing"); + let nodes = settled(&mut app, &ctx, 0.5, 1400.0); + let tool = nodes + .iter() + .find(|n| n.role() == Role::ListBoxOption && n.label().is_some_and(|label| label.starts_with("Scissors"))) + .expect("the native palette lists the matching Scissors tool"); + assert!(!tool.is_disabled()); + click(&mut app, &ctx, 0.7, bounds(tool).unwrap().center(), 1400.0); + assert_eq!(app.session.tool_id(), "scissors", "activating the real result chooses the tool"); + assert!(!app.ui.palette_open, "a pick closes the palette"); + assert_eq!(app.ui.recent_commands.first().map(|command| command.key_text().into_owned()), Some("tool:scissors".to_string())); + assert_eq!(review_8758_unchanged_content(&app), before, "choosing a tool changes no artwork/history or toolbar membership"); + + // Current main owns query state inside CommandPalette and resets it on opening. A blocked footer press must not + // open that component at all, invoke a command, steal focus or change the existing real dialog's fields. + open_options(&mut app, "lineSegment").unwrap(); + let nodes = settled(&mut app, &ctx, 1.0, 1400.0); + let dialog = tool_dialog(&app).expect("the real Tool Options dialog"); + let focus = craft::ui::runtime::focus::focused_rec(&ctx); + let runs = app.run_count; + let recent = app.ui.recent_commands.clone(); + let search = review_8758_button(&app, &ctx, &nodes, "Search commands"); + assert!(search.is_disabled(), "screen readers find Search disabled while a modal window is open"); + click(&mut app, &ctx, 1.2, bounds(search).unwrap().center(), 1400.0); + assert!(!app.ui.palette_open, "the disabled footer cannot open Search over a dialog"); + assert_eq!(app.run_count, runs, "the disabled footer does not invoke the palette command"); + assert_eq!(craft::ui::runtime::focus::focused_rec(&ctx), focus, "the existing modal keeps focus"); + assert_eq!(app.ui.recent_commands, recent); + assert_eq!(tool_dialog(&app), Some(dialog)); + assert_eq!(review_8758_unchanged_content(&app), before); +} + /// A window too short for the tools shows the rail's scroll bar with the pointer away from the rail: a narrow bar, /// several times taller than wide, inside the rail's end edge. A window tall enough for every tool shows none. #[test] diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 341c0c4113..183d7bbe7e 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -140,7 +140,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool /// dialog is open (its OK acts on the active document, which a trace's result changes), nor while /// an interaction is open or a tool drags with the pointer button held, as [`crate::placing::poll`]. pub fn poll(app: &mut VectorcraftApp) { - if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { return; } let mut i = 0; @@ -153,15 +153,30 @@ pub fn poll(app: &mut VectorcraftApp) { } Err(TryRecvError::Disconnected) => None, }; - let r = app.trace_runs.running.remove(i); - // The status bar no longer says it is tracing. - if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { - app.ui.status.clear(); - } - finish(app, r, done); + land(app, i, done); } } +/// Waits for each trace running to end, in the order they were started, and applies it as +/// [`poll`] does once it is done. +#[cfg(test)] +pub(crate) fn finish_all(app: &mut VectorcraftApp) { + while let Some(r) = app.trace_runs.running.first() { + let done = r.done.recv().ok(); + land(app, 0, done); + } +} + +/// Takes trace `i`, which has ended with `done`, off the list and applies it. +fn land(app: &mut VectorcraftApp, i: usize, done: Option) { + let r = app.trace_runs.running.remove(i); + // The status bar no longer says it is tracing. + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + /// Applies trace `r`'s result in its document, which becomes the active one again, as its command /// would while the object, its image and the settings are as they were and the document was not /// reverted; else why it has none, in the status bar. diff --git a/crates/ui-egui/tests/menu_access_keys.rs b/crates/ui-egui/tests/menu_access_keys.rs index c837734c99..f2a04cd75a 100644 --- a/crates/ui-egui/tests/menu_access_keys.rs +++ b/crates/ui-egui/tests/menu_access_keys.rs @@ -164,10 +164,22 @@ fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() { assert_eq!(s.app.session.tool_id(), "pen", "after the dismissal the letter selects its tool"); s.app.select_tool("selection"); - // While the bar holds the keys after a lone Alt, the letter does not reach the tool either. + // A lone Alt over the canvas is a tool modifier let go: the bar does not take the keys, and the next tool + // letters choose their tools instead of opening View or Window. s.bare_alt(); s.settle(); - assert!(is_focused(&s.ctx), "a lone Alt gives the bar the keys"); + assert!(!is_focused(&s.ctx) && !is_open(&s.ctx), "a lone Alt over the canvas leaves the bar alone"); + s.letter(Key::V, "v", Modifiers::NONE); + assert!(!is_open(&s.ctx), "V after a lone Alt opens no menu"); + s.letter(Key::P, "p", Modifiers::NONE); + assert_eq!(s.app.session.tool_id(), "pen", "P after a lone Alt chooses the Pen"); + s.app.select_tool("selection"); + + // While the bar holds the keys after F10, the letter does not reach the tool. + s.frame(vec![key(Key::F10, true, Modifiers::NONE)]); + s.frame(vec![key(Key::F10, false, Modifiers::NONE)]); + s.settle(); + assert!(is_focused(&s.ctx), "F10 gives the bar the keys"); s.letter(Key::P, "p", Modifiers::NONE); assert_eq!(s.app.session.tool_id(), "selection", "a focused bar takes the letter"); s.click(outside); diff --git a/crates/ui-egui/tests/menu_on_second_monitor.rs b/crates/ui-egui/tests/menu_on_second_monitor.rs new file mode 100644 index 0000000000..30fd5f6363 --- /dev/null +++ b/crates/ui-egui/tests/menu_on_second_monitor.rs @@ -0,0 +1,110 @@ +//! A menu bar menu opens under its title when the window sits on a second monitor that does not start at a multiple +//! of its own size (a landscape monitor beside a portrait one, their bottoms aligned). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Arc, Mutex}; + +use craft::behavior::{Monitor, MonitorKey}; +use craft::ui::testing::windows::FakeSystem; +use egui::accesskit::Role; +use egui::{Event, Pos2, RawInput, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::{VectorcraftApp, i18n}; + +// Integration tests link the production global shortcut mirror; each App owns it until its case ends. +static INPUT: Mutex<()> = Mutex::new(()); + +/// The window's content size in pixels, below a 44 px title bar on the landscape monitor. +const WINDOW_PX: [f32; 2] = [1920.0, 1156.0]; +/// Where the window's content starts on the desktop, in pixels. +const WINDOW_AT_PX: [f32; 2] = [1200.0, 764.0]; + +/// A portrait monitor at the desktop's origin and a landscape one to its right, their bottoms aligned. +fn monitors(scale: f32) -> Vec { + let portrait = Monitor::new(MonitorKey::new("portrait", [1200, 1920]), [0, 0], [1200, 1920], scale); + let landscape = Monitor::new(MonitorKey::new("landscape", [1920, 1200]), [1200, 720], [1920, 1200], scale); + vec![portrait, landscape] +} + +struct Scene { + app: VectorcraftApp, + ctx: egui::Context, + time: f64, + scale: f32, +} + +impl Scene { + fn new(scale: f32) -> Self { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let system = FakeSystem::new(); + system.set_monitors(monitors(scale)); + let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(system)); + craft::ui::shell::embed::install(&ctx, spec, &vectorcraft_ui_egui::ui_fonts()).unwrap(); + Self { app, ctx, time: 0.0, scale } + } + + /// One frame of the whole window; returns the accessibility nodes with their bounds. + fn frame(&mut self, events: Vec) -> Vec<(Role, String, Rect)> { + self.time += 1.0 / 30.0; + let points = |[x, y]: [f32; 2]| pos2(x, y) / self.scale; + let size = points(WINDOW_PX).to_vec2(); + let mut raw = + RawInput { events, time: Some(self.time), focused: true, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), ..Default::default() }; + let viewport = raw.viewports.entry(egui::ViewportId::ROOT).or_default(); + viewport.native_pixels_per_point = Some(self.scale); + viewport.monitor_size = Some(vec2(1920.0, 1200.0) / self.scale); + viewport.inner_rect = Some(Rect::from_min_size(points(WINDOW_AT_PX), size)); + viewport.outer_rect = Some(Rect::from_min_size(points(WINDOW_AT_PX) - vec2(0.0, 44.0 / self.scale), size + vec2(0.0, 44.0 / self.scale))); + craft::ui::shell::embed::before_input(&self.ctx, |out| self.app.frame_input(out)); + let mut out = self.ctx.run_ui(raw, |ui| self.app.ui(ui)); + let _ = self.app.frame_input(craft::ui::runtime::frame::take_output(&self.ctx)); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update.take().unwrap(); + update + .nodes + .into_iter() + .filter_map(|(_, node)| { + let b = node.bounds()?; + let rect = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)); + Some((node.role(), node.label().unwrap_or_default().to_string(), rect)) + }) + .collect() + } +} + +#[test] +fn the_file_menu_opens_under_its_title_on_a_monitor_beside_a_portrait_one() { + let _input = INPUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let previous = i18n::current(); + i18n::set_current(i18n::Lang::EN); + for scale in [1.0, 1.5] { + let mut scene = Scene::new(scale); + for _ in 0..3 { + scene.frame(vec![]); + } + let nodes = scene.frame(vec![]); + let title = nodes.iter().find(|(role, label, _)| *role == Role::MenuItem && label == "File").map(|(_, _, rect)| *rect); + let title = title.unwrap_or_else(|| panic!("no File title at {scale}x: {nodes:?}")); + let at = title.center(); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + scene.frame(vec![Event::PointerMoved(at)]); + scene.frame(vec![button(true)]); + scene.frame(vec![button(false)]); + let nodes = scene.frame(vec![]); + let menu = nodes.iter().filter(|(role, _, _)| *role == Role::Menu).map(|(_, _, rect)| *rect).next(); + let menu = menu.unwrap_or_else(|| panic!("the File menu did not open at {scale}x: {nodes:?}")); + // The menu's list sits inside the popup's frame, a few points in from the title's corner. + assert!( + (menu.left() - title.left()).abs() <= 8.0 && (menu.top() - title.bottom()).abs() <= 8.0, + "at {scale}x the File menu opens at {menu:?}, not under its title at {title:?}" + ); + // The whole menu shows: the window's content lies on the landscape monitor, so nothing cuts its room. + let items = nodes.iter().filter(|(role, _, rect)| *role == Role::MenuItem && menu.contains_rect(*rect)).count(); + assert!(items >= 15, "at {scale}x the File menu shows {items} items in {menu:?}"); + } + i18n::set_current(previous); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..21c81bda1e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -194,8 +194,10 @@ for `eyedropper` it opens Eyedropper Options, an `eyedropperOptions` dialog (fie `apply`, the attribute trees of `eyedropper.setOptions`) whose `ui.dialog.confirm` runs `eyedropper.setOptions` (what `appearance.copyFrom` copies). For `hand` it fits the artboard in the window (`view.fitArtboard`) and for `zoom` it shows 100% (`view.actualSize`). For `rotate`, `scale`, `reflect` and `shear` it opens the same dialog as Object › -Transform (dialog kind = the tool id), or fails with `nothing selected`. For `selection`, `directSelection` and -`groupSelection` it opens the Move dialog (kind `move`), with the same failure; Move opens on the offset of the last +Transform (`key` in `ui.inspect`: `object.`, such as `object.rotate`), or fails with `nothing selected`. +The returned `dialog` field holds `rotate`, `scale`, `reflect` or `shear`, respectively. For `selection`, `directSelection` and +`groupSelection` it opens the Move dialog (`key` in `ui.inspect`: `object.move`), with the same failure, and returns +`dialog: "move"`. Move opens on the offset of the last drag or Move (`dx`, `dy`) and with the `copy`, `objects` and `preview` it was last confirmed with (its `patterns` is the `transformPatternTiles` preference, which its OK sets). `ui.key` Enter with one of those seven tools opens its dialog too (nothing happens without a selection), with the transform tools' `origin` at their reference @@ -203,8 +205,9 @@ point. For `lineSegment`, `arc`, `rectangularGrid` and `polarGrid` it opens the click opens (kind = the tool id), without `x` and `y` and with `__toolOptions: true`, whose `ui.dialog.confirm` runs `tool.setOption {tool, values}` and draws nothing; the next drag with the tool and its click dialog use the values (the line's `fillLine`, the grids' Default Size `width`, `height` and `reference` too). For `typeOnPath` and -`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (a `command` dialog running -`type.pathOptions`), or fails when no type on a path is selected. Gradient tool handles snap to +`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (`key` in `ui.inspect`: +`type.pathOptions`, which runs that command), or fails when no type on a path is selected. The returned `dialog` field +holds `command`. Gradient tool handles snap to anchors, edges and smart guides; Shift constrains them to 45° steps from the `constrainAngle` preference. Effect dialogs: `engine.execute {command: "effect.dialog", params: {effect, index?, item?}}` opens the `effect` dialog @@ -597,7 +600,7 @@ keeps the dialog's options as a saved preset. PDF presets: `ui.pdfPresetsDialog {selected?}` opens Edit → PDF Presets (dialog `pdfPresets`, field `selected`: a preset name). Built-in presets are read-only. New… and Edit… open the preset editor, which `ui.pdfPresetDialog {name? -(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdfPreset`, the Save PDF +(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdf-export`, the Save PDF dialog's option fields plus `name` and `description`; `ui.dialog.confirm` runs `pdf.preset.save` and returns to PDF Presets (a new preset can't take a name in use). Delete, Import… and Export… are `pdf.preset.delete`, `pdf.preset.import` and `pdf.preset.export`; `ui.dialog.confirm` closes. Opening a `.vcpdfpresets` file with `app.open` @@ -637,9 +640,9 @@ Spot Colors: the Swatches panel menu's Spot Colors… (`ui.spotColors`) opens th true shows and separates spot colours defined in Lab from their Lab values, false from their working-CMYK equivalents); `ui.dialog.confirm` runs `swatch.spotOptions {useLab}` as one undo step. -Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `scale`, +Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `object.scale`, `object.transformEach` → `transformEach`, also Move, Rotate, Reflect, Shear and the Path dialogs). The Scale dialog -(`scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`, +(`object.scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`, `scaleV` %, and `absH`, `absV` pt, the width and height each object becomes with `relative` false, absent while they read "Mixed"; `moveH`, `moveV` pt, `rotate` °, `reflectX`, `reflectY`, `random`, `reference` 0–8, `copy`, `preview`) have the fields `corners` (Scale Corners) and `strokes` (Scale Strokes & Effects). They start from the preferences @@ -754,7 +757,7 @@ the dock's tab strip while Layers shows) lists the layer commands (New Layer…, Options for Selection…, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers, Reverse Order, Template, Hide/Outline/Lock Others or Show/Preview/Unlock All Layers), Paste Remembers Layers (`layer.pasteRemembersLayers`, checked when on) and Panel Options…. Layer Options is the -`layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `layersPanelOptions` +`ui.layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `ui.layersPanelOptions` dialog (`ui.layersPanelOptions`), and `ui.layersExpand {ids?, open?}` opens or closes rows; see the Layers panel section of `docs/mcp.md` for the row commands (`layer.setCurrent`, `layer.highlight`, `layer.move`…). @@ -766,10 +769,10 @@ File Info: File → File Info… (`file.info` from the menu or Cmd+Alt+Shift+I; stays open. Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for -agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports +agents) opens the `document.rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports (`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`); -`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a -`command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, +`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens the +`object.rasterize` dialog, whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround`) start from these settings. `colorModel`, `antiAlias` (`none`, `art`, `type`) and `background` (`white`, `transparent`) are dropdowns; `ui.dialog.set` also takes any other value the command takes, and the dialog sends it unchanged. @@ -881,7 +884,7 @@ art too large at that scale) keeps the dialog open. Placement Options: the Links panel's flyout (or `ui.placementOptionsDialog {ids?}` for agents) opens the `placementOptions` dialog for the selected images (fields `ids`, `preserve`: `transforms`/`bounds`/`fileDimensions`/ `fit`/`fill`, `align`: `topLeft` … `bottomRight`, `clip`). `ui.dialog.confirm` runs `links.placementOptions` with them as -one undo step. +one undo step, on the images the dialog opened on even when the selection has changed since. Relink: the Links panel's Relink… button and flyout item (or `ui.relinkDialog {ids?}` for agents) open the `relink` dialog for the selected images and placed documents (fields `ids`, `links`: `[{name, ids}]`, one row per linked file, @@ -994,7 +997,7 @@ the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster r rows off; RLE turns flipped rows off). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with `document.export`. -Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `saveForWeb` +Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `save-for-web` dialog on the remembered settings (`webExport.settings`). Its fields are the `document.exportForWeb` settings (`format`, `colors`, `reduction`, `dither`, `quality`, `colorTable`, `width`, `percent`, `output`…; set `preset` to load a preset) plus `__view` (`original`, `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` and @@ -1074,7 +1077,7 @@ Colour adjustment effects (Effect → Color Adjustments) open the `effect` dialo `channel` for Curves and Levels, `points` for Curves, `color` for Shift to Color) and they preview live; set them with `ui.dialog.set` and `ui.dialog.confirm` to apply (Curves also has a graph: drag its points). Object → Vector Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "object.vectorHalftone"}}`) opens the -`vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`, +`object.vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`, `preview`): it previews live and `ui.dialog.confirm` keeps the halftone as one undo step. Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..6f43d470b9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -74,6 +74,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - **Automatic on Linux and the BSDs** is the GPU that drives the panel or a monitor, then the system's order: Mesa's Vulkan device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid laptops; `DRI_PRIME` and `MESA_VK_DEVICE_SELECT` steer it). A Wayland compositor may not accept frames from another GPU: on a desktop whose compositor ran on an NVIDIA GPU, rendering on the Ryzen's integrated GPU made KWin end the window's connection ("importing the supplied dmabufs failed") and 0.5.0 crashed at startup (#502). - 0.5.0 saved `powerSaving`, its default, for everyone; it reads as `automatic`. - **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`, #651). The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking. +- **If no graphics adapter can show the window at all** on Linux or a BSD, the app starts once more on Mesa's software renderer (llvmpipe, through `LIBGL_ALWAYS_SOFTWARE=1`), which draws on the CPU and is slower, and says so in the status bar. That covers every adapter left out by the restarts above, and a GPU whose driver offers none of the backends wgpu draws with: Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (PCI id `8086:0046`, in a ThinkPad T510) has OpenGL 2.1 alone, so wgpu started no backend and the window failed with `Failed to create surface for any enabled backend: {}` (#2654). The software start carries `VECTORCRAFT_GPU_SOFTWARE`, so it happens once; when it fails too, or when `WGPU_BACKEND`, `WGPU_ADAPTER_NAME` or `LIBGL_ALWAYS_SOFTWARE` is set, the app exits with an error that names the backends the driver needs. On a laptop with a second GPU, choosing that GPU in the firmware settings may give a driver with one of these backends. - **If the window's first frame never reaches the screen** within 20 seconds of the app being created (the files named at the start opened), the adapter counts as hanging and the app starts again without it in the same way (#964: High Performance on a hybrid laptop left the app running in the background with no window and nothing in the log). A window minimized at the start isn't counted. When the processor that hung was chosen in Preferences, the status bar points to Automatic. - **If the app crashes while the window starts**, as when Intel's Direct3D 12 driver (`igd12umd64.dll`) ended 0.9.0 before its window appeared on an Intel UHD Graphics 605 (#2243), no code in the process runs to start it again, so the next start leaves the adapter out. Each start writes `graphics-start.json` in the log folder before the graphics start and adds the adapter once one is picked; when the first frame reaches the screen or the app ends without crashing, the start is cleared from the file. A start that finds an earlier start still recorded there logs the adapter, leaves it out and shows a note in the status bar. When the crash came while the adapters were being listed (wgpu's Direct3D 12 backend creates a device on each GPU to list it), the next start lists OpenGL's adapters alone; on macOS, where wgpu has no OpenGL adapters, it lists them all. Later starts keep leaving them out until the app version or Preferences › Performance › Graphics Processor changes, a start shows its first frame on the adapter that crashed, or no adapter is left that can show the window. `WGPU_BACKEND` and `WGPU_ADAPTER_NAME` choose regardless of the file: a start with `WGPU_BACKEND=dx12` tries Direct3D 12 again, and when its first frame appears, the crash is cleared. A process ended from outside during the start (Task Manager, `kill`) counts as a crash. Runs without preferences (`VECTORCRAFT_NO_PREFS`) record nothing, and a start made while another copy of the app is starting neither reads nor writes the file. - **To recover from a Graphics Processor choice that doesn't work** without editing files: start once with `WGPU_POWER_PREF=low` (or `WGPU_ADAPTER_NAME=…`), which overrides the preference for that start while settings still save, and set Graphics Processor back to Automatic. `VECTORCRAFT_NO_PREFS=1` also starts without it, but saves nothing. @@ -109,6 +110,7 @@ When the interface thread stays in one part of a frame for 3 s (VectorCraft's ow | `WGPU_ADAPTER_NAME` | Graphics adapter by (part of) its name, any case (see [Desktop graphics processor](#desktop-graphics-processor)) | | `WGPU_BACKEND` | Graphics backends: `vulkan`, `dx12`, `metal`, `gl` | | `VECTORCRAFT_GPU_SKIP` | Set by the app when it starts again without a graphics adapter that failed (see [Desktop graphics processor](#desktop-graphics-processor)) | +| `VECTORCRAFT_GPU_SOFTWARE` | Set by the app, with `LIBGL_ALWAYS_SOFTWARE=1`, when it starts again on Mesa's software renderer because no graphics adapter could show the window (Linux and the BSDs; see [Desktop graphics processor](#desktop-graphics-processor)) | | `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) | ## macOS: the menu bar @@ -134,7 +136,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --nosocket=fallback-x11 --socket=x11 ai.storyteller.vectorcraft` gives it one and keeps its Wayland socket. `--socket=x11` alone is not enough: while `fallback-x11` is set, Flatpak gives the app no X display whenever Wayland is available. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. @@ -292,7 +294,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE placeholders and ellipses agree, command ids exist, every row of a partial catalog is a string the UI shows, the UI fonts have every glyph, no Simplified characters in `zh-hant`) pick it up. Set `complete_menus` once the menus and `tl!` literals are translated; the untranslated report then lists what the catalog lacks - (`VECTORCRAFT_I18N_DUMP=strings.txt cargo test -p vectorcraft-ui-egui dump_source_strings` lists every + (`VECTORCRAFT_I18N_DUMP=strings.txt cargo test -p vectorcraft-ui-egui dump_source_strings -- --ignored` lists every English string). - A missing translation never fails a test or a build: the interface shows the English text until a translator adds the row. `cargo xtask i18n-report` prints, per language, the strings its catalog lacks (menu strings, @@ -327,7 +329,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE `bad(…)` or `failed(…)`, and the messages a `.map_err(|e| …)` closure returns (from each `if` branch, `match` arm and statement of a block) or the handler a `.map_err(name)` names returns (a closure bound with `let name = |e| …;` or a function `fn name(…)`), and skips calls inside comments - (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui dump_source_strings` lists them + (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui dump_source_strings -- --ignored` lists them all). A missing row shows the English message. Other languages show messages in English until they add `@msg` rows. - Not translated on purpose: names that are user data (layers, swatches, fonts, documents), the tab @@ -349,6 +351,10 @@ The app decides which cursors exist; whoever draws them works from the list. For `cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. +## Test lint + +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. + ## Tests - `cargo xtask test` runs the workspace's unit and integration tests with diff --git a/docs/dimensions.md b/docs/dimensions.md index ab5003a2b9..a7359497aa 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -93,8 +93,8 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions by holding Alt - (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's - outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when + (Option on macOS) over its path. With Alt held, hovering a path shows the box the path's strokes + paint (described below), as a Smart Guide when Smart Guides are on and in the tool's own color when they are off, with its width and height beside the pointer when Measurement Labels are on. Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out from the path places it on release. The rest is VectorCraft's own rule. With @@ -105,12 +105,14 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers that starts no segment is left out. They are read again whenever the path changes, so a turned path shows its new overall width or height rather than that of its bounding box before the turn. The line keeps its distance from the whole path when the path changes or the dimension - changes orientation. With Use Preview Bounds on, the box and the dimension reach the outside of - the path's strokes, the width or height that W and H show: each outermost point moves out to the - edge of the box the strokes paint (a member of a compound path takes the compound path's - strokes, with an arrowhead only where the compound path draws one on that member), and a dimension placed that way measures to there again when the path or its strokes - change. Geometry effects are not included. Alt has this effect only before the first point is - clicked. + changes orientation. With Use Preview Bounds on or off, the box and the dimension reach the + outside of the path's strokes, the width or height that W and H show with Use Preview Bounds + on: each outermost point moves out to the edge of the box the strokes paint (a member of a + compound path takes the compound path's strokes, with an arrowhead only where the compound path + draws one on that member), and a dimension placed that way measures to there again when the + path or its strokes change. Geometry effects are not included. A dimension of a whole path saved + without `"preview":true` keeps measuring between the outermost points. Alt has this effect only + before the first point is clicked. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -205,7 +207,7 @@ another document. `vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":}` measures a whole path, linear only: between its leftmost and rightmost points when horizontal or aligned, and its topmost and bottommost points when vertical. With `"preview":true` (what - the tool records with Use Preview Bounds on; `false` when omitted, and any value other than + the tool records for an Alt-placed dimension; `false` when omitted, and any value other than `true` or `false` is an error) those points move out to the outside of the path's strokes. A version without the extent source does not open a file that holds one, and a version without `preview` measures such a dimension between the points themselves. `offset` is the distance of diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 2e4ef4dd15..0adea74366 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -13,7 +13,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---:|---:|---:|---:| | Illustrator effects (vector and stylize) | 50 | 50 | 100% | — | | Photoshop effects (raster, Effect Gallery) | 57 | 57 | 100% | — | -| 3D and Materials | 4 (+3 Classic) | 4 (+3 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic), Revolve (Classic), Rotate (Classic)) | ~25% | 25–45 | +| 3D and Materials | 4 (+3 Classic) | 4 (+3 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic), Revolve (Classic), Rotate (Classic)) | ~35% | 25–45 | | Beyond Illustrator: Effect › Color Adjustments (6), effect plug-ins (WebAssembly) | — | 6 + plug-ins | — | — | ## Illustrator effects diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6287e13f47..a38623c2fe 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. +> > **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -59,9 +61,9 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 34 | missing: FreeHand, DWG | +| Formats opened or placed | ~30 | 36 | missing: FreeHand, DWG | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | -| Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | +| Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | EPS editing-data follow-up (2026-10-16): both mesh-corner layouts (with and without opacity) @@ -139,8 +141,15 @@ private editing data. VectorCraft: instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art, pattern fills in a symbol's art are written as their tiles cut to the shape, symbols past 4,096 are written only as their - instances' art, and symbols' 9-slice guides, export types and dynamic type are left out, each with a - warning. Paths, compound paths and groups with live effects keep them as art styles: the drawn look, the object + instances' art, and symbols' 9-slice guides and export types are left out, each with a + warning. A dynamic symbol instance whose only changes of its own are its parts' changes is not written as its + art when it otherwise qualifies: it stays a live instance. The symbol's dynamic type and the instance's changes + are written in VectorCraft's own entries, which VectorCraft reads back and other apps leave out; writing the + changes gives a warning, and writing the dynamic type alone does not. The changes name the symbol's parts by + their place, so they are reproduced only where the editing copy keeps the symbol's parts as they are: fill and + stroke changes to type, which the copy holds as outlines, are not reproduced (opacity and blend changes are), and + when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none. When an instance's + changes together take more than 1 MiB, none of them is written, without a warning. Paths, compound paths and groups with live effects keep them as art styles: the drawn look, the object itself and the style it names, for a fill and a stroke at most in solid colors or the object's gradient (a stroke with its variable-width profile), filled by the non-zero rule, with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Convert to Shape, Offset Path, Outline Object or Outline Stroke, and groups with Pathfinder › @@ -331,13 +340,13 @@ private editing data. VectorCraft: An image whose color space `XC` sets to one ink (`n [… (name) /Separation] XC`) comes in as a grayscale image of its tints (black at 100 %) colorized by the ink (its spot swatch, or a process plate's CMYK color), its alpha channel as its opacity mask (#6350). -- Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy +- Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible with an editing copy of the art (`editingData`, on by default), or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. ### Illustrator's private editing data -The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip, its clipping paths grouped in it, at any depth, included; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Stylus Wheel, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip, its clipping paths grouped in it, at any depth, included; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Stylus Wheel, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's, other than the changes VectorCraft writes in its own entries), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. A Scatter brush's art comes in turned over from its section, as an Art brush's does: in each copy the side of the section with y up goes down the page before the copy's rotation, and the writer writes the art back the same way. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. @@ -359,7 +368,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); an image of more than 2^26 pixels is read at a lower resolution (every second, third… sample of every second, third… row), not left out, with a note; when its data is more than the reader holds, Flate or LZW compressing it last (without a predictor) is decoded keeping only the rows read; sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | @@ -425,6 +434,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-30 | minor | `.ai` and EPS import: a word the page draws from two text objects in a row is their type. Where the text document makes the type of every text object that shows, a word of the page's type is the type of the made type holding its piece when that type spells it. The page can draw two text objects as one word: a word and a letter set apart from it (a swash "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. It was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), though both text objects come in and draw it. Now a word left that is the last word of one text object holding the piece joined to the first word of another holding it that draws after it, along the first one's lines, is theirs (`joined_by_two` in `see_page_type`). Each part is a whole word of its text object, and the two the other way round don't make the word. Tests: `a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type`, `two_text_objects_the_other_way_round_arent_the_word_the_page_draws`. | | 2026-11-27 | minor | `.ai` save: type in a spot ink, a global process colour or Registration keeps its swatch link and its tint. Its fill and stroke in the text document name (key 5 of the paint) an art style of one paint, `0 1 Xd`, whose paint is the colour as a path's fill writes it (`x`, `Xx`, `Xk`, `Xs`), the form `.ai` import reads since the change below; key 0 still holds the process values at the tint. Each style is read back before it is written and kept only when the reader gives the same swatch and tint, so such type no longer counts among the attributes of type left out; a link to a process swatch that isn't global still does. Test `ai_editing::tests::type_in_spot_and_global_colors_reads_back_linked_at_its_tint` | | 2026-11-27 | minor | `.ai` and EPS import: type set in a spot ink or a global process colour keeps its ink. In the text document a character's fill or stroke is a colour (key 0: grey, RGB or CMYK) and the name of an art style (key 5). In users' files (used locally, never committed) that style is one paint (`/SimpleStyle`), always its fill's, for a stroke too; for a spot ink or a global process colour it is `c m y k (name) tint x`, `Xx` or `Xk`, and key 0 keeps only the ink's process values at that tint. Such type came in as that process colour, so it separated onto the process plates, and white type in a white ink onto none. It now takes the style's paint: the colour at its tint, linked to the document's swatch of that name, which the style's colour makes when the art doesn't (after the art's colours, before the header's custom colours). A style whose paint is a process colour or a gradient, one that also sets a stroke's colour or pattern (before or after the fill's) or another fill paint after it, one whose `Xd` doesn't turn on its fill alone, and a paint that names no style of the file, keep the colour of key 0 as before; type filled with a gradient still comes in black. Tests `type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names` in `crates/eps/src/import/tests_native.rs`, `a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch` in `crates/eps/src/import/ate.rs` and `only_a_style_of_one_swatch_colour_holds_it_for_type` in `crates/eps/src/import/ai/style/tests.rs`. Scores and estimates unchanged. | | 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. A file whose layers failed the comparison that way and opened without it now passes it and shows its notes. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws`, `centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. | @@ -457,6 +467,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | | 2026-11-07 | minor | EPS import: an image of more than 2^26 pixels (the reader's cap) was left out, so a page that is one large scan or photo came in empty. It is now read at a lower resolution: the least whole step that brings it within the cap, the middle sample of each step × step block, over the image's whole area, with the note *images of more than 67 million pixels were read at a lower resolution*. When its samples are more data than the reader holds (256 MB), an image whose last filter is Flate or LZW without a predictor is decoded a row at a time, keeping only the rows read (an 11903 × 8423 RGB page, 300 MB, comes in at 5952 × 4212). An image left out still has its data skipped (#6003), now also when a procedure reads it (called until it has given the image's data or ends) and when its first filter decompresses to more than the reader holds (the compressed data is measured without keeping it). Tests `an_image_over_the_pixel_cap_is_read_at_a_lower_resolution`, `an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads`, `the_data_of_an_image_too_large_to_hold_is_skipped`; scores unchanged | | 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | `.ai` and EPS import, and what SVG export, PDF export and `.ai` save draw: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as a `.ai`'s own page aligns them (see type-parity.md, same date). In 224 users' files (used locally, never committed), 63 render differently: 54 closer to the page, 7 further, 1 alike and 1 that couldn't be compared; among them the median share of pixels that differ from the page went from 4.4% to 1.0%. Of the 7: one now opens from its layers instead of its PDF part (they differ from the page by less than the import's 5% limit now; type note 3.8%); one has a centred line whose spacing inside it differs from the page's, which now centres on the page's line while half of it no longer lies on the page's glyphs (type note 1.4% to 2.4%); five moved by less than 0.05 of a percentage point, in type the page draws in other glyphs. The type note shows a smaller share in 6 files; 2 more envelopes of type open live (129 to 131, none fewer in any file). SVG import: `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, so a centred or right-aligned letter-spaced line moves back by half or all of it and stays where a reader draws it; SVG export, which anchors lines so, reads back unchanged (test `import_text::anchored_letter_spaced_lines_stay_where_a_reader_draws_them`). Affinity import: centred or right-aligned tracked artistic text moves by half or all of its last character's tracking, as layout now aligns it (unverified against Affinity, whose files we don't have), and differently aligned paragraphs line up by the widths layout aligns them by (`affinity_features::artistic_text_aligns_its_lines_within_the_longest`). Scores and estimates unchanged. (#6610) | diff --git a/docs/gaps.md b/docs/gaps.md index 9130e782f1..671283d648 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,7 +1,7 @@ # Gaps > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -23,16 +23,22 @@ Properties panel Quick Actions follow the whole selection (G12). Ungroup (`objec History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. +**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. + OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + - **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Appearance panel row context menus (part of G12): right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Evidence: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, and `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance` in `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -185,7 +191,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. -- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -197,7 +203,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Polygon/Star count persistence:** Exact-size placement saves the chosen count for later drags and reopening the existing canvas dialog. Regression coverage includes both tools, repeated drags, switching tools and Cancel. The remaining G1 scope and estimates are unchanged. -- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. +- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. - **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. Broader scope and estimates unchanged. @@ -398,8 +404,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools -- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. -- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. +- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/it/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. +- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. - **Implemented (#6470):** Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping, following the existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions are in `crates/tools/src/draw2/anchor/tests.rs`; broader G11 scope and estimates unchanged. @@ -465,6 +471,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi such stubs into one vertex (within 4× the sweep's tolerance up and down its frame and 1/16 of the 0.01 pt precision along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. +- **Done (2026-11-03):** SVG Options › Units (`units`) explicitly overrides `width` and `height` with `px` + (bare numbers; CSS pixels are 96 per inch), `pt`, `mm`, `cm` or `in`, with the `viewBox` in points (#4462). + Responsive omits both dimensions; unknown units and explicit null are errors. Without an override, export + retains the document's physical units as below. Estimate unchanged. - **Done (#864):** SVG export writes physical unit suffixes on the root `<svg width="..." height="...">` for documents with physical units (`mm`, `cm`, `in`, `pc`; documents in feet and yards are written in `in`, in meters in `cm`, and in Q or Ha in `mm`, since SVG has no unit for them: `every_physical_document_unit_exports_its_printed_size`), so external vector tools (Inkscape, LightBurn) and browsers render drawings at their intended physical scale rather than scaling to 75% under point-based user-unit assumptions; unitless user coordinates in `viewBox` and path geometry remain in 1:1 internal points per SVG 1.1 coords §7.10. A round trip keeps `mm`, `cm`, `in` and `pc` documents in their unit (`export_physical_units_writes_unit_suffixes`, `svg_round_trip_preserves_document_units`); documents in feet, yards, meters, Q or Ha keep their printed size and open again in the SVG unit they were written in. General document unit preferences across restarts remain tracked under #864. - **Missing:** general document unit preference on restart (#864; SVG export physical units done). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) @@ -549,6 +559,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. + - **Implemented and tested (2026-11-21):** Properties panel Quick Actions follow every selected object. Ungroup (`object.ungroup`) is offered when any selected object is a group, including several groups, a group selected after a path, and a group that holds another group. Isolate Group (`object.isolate`) is offered only when that one group is the whole selection. Unite (`object.pathfinder.unite`) appears only for selections of at least two objects, each a non-guide path or a compound path. It appears alongside Group and Make Clipping Mask. Headless regressions: `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group` and `several_paths_offer_group_clipping_mask_and_unite`. Other G12 gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-21):** Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`; kept in memory for the session, not stored) asks `document.info` for the selection: object counts cover the selected nodes and their descendants, and with no artwork selected it shows `(No artwork selected)` instead of the document's counts, while artboards the Artboard tool has selected still show under Document. With the item off, counts stay for the whole document. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. @@ -851,6 +863,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi character and paragraph attributes, their links to each other and the stories they form, its character and paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. + Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a + document's `fullName`, `path` and `saved`, and close it with `Document.close`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and @@ -1047,6 +1061,8 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | +| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | @@ -1108,6 +1124,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-05 | minor | G15: a document's first frame renders on the render worker (#4155); the longest UI-thread stall opening that file went from 8.7 s to 64 ms. Estimate unchanged. | | 2026-11-05 | minor | G15: a reduced image is shrunk before it is separated into ink planes (#4155); first frame 9.2 s → 1.6 s, sharp frame after a pan 3.9 s → 8 ms on that file. Estimate unchanged. | | 2026-11-05 | minor | G7: document tabs are dragged along the tab strip to reorder them (`document.move`, #5663). Estimate unchanged. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before; to export physical dimensions turn Responsive off and choose Points, Millimeters, Centimeters or Inches, since Responsive omits `width` and `height`); scores and estimates unchanged | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | @@ -1318,4 +1335,4 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 2f77e494bb..cc7c4c656c 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -25,7 +25,7 @@ It reads the pen's tilt and barrel rotation on Windows with Windows Ink (#372), | Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none (an Art brush's Width, a Pattern brush's Scale and Bristle brushes follow them, #8490); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch-screen rotation missing (the Touch workspace ships, #3139), 3–5 h | -| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | +| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | smooth scroll; pinch and rotate on native Wayland where the compositor offers pointer gestures (#5981), not under X11 or XWayland | yes | done | | HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated | | Multiple monitors: panels and document windows on another screen | yes | yes: floating panels (#4135) and floating document windows (#5278) are OS windows, and a floating panel reopens on the monitor where it was left (#6038) | yes | under X11; on Wayland they are windows inside the main window | — | partial: Wayland remains, 6–10 h (with multiple windows, gap G7) | | Display colour profile (proof and display through the monitor's ICC) | yes | yes: the window is tagged sRGB and macOS converts it | yes: the display's default ICC profile, Windows' own conversion with Advanced Color on | X11: colord or `_ICC_PROFILE`; Wayland: sRGB | — | done on macOS, Windows and X11; Wayland and floating document windows remain | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 555cc17f7f..fe10d21a97 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** patch (Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; UI not exposed pending upstream `storytold/craft-i18n` catalog; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) Per-language status of VectorCraft's interface. How the catalogs work and how to add a language: [`development.md` › Localisation](development.md#localisation). Part of @@ -24,7 +24,7 @@ English) in-app help, and the docs are English. (`bflatastic`), with community contributors adding or correcting (German by `dwetscher`, Japanese and Traditional Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded as reviewed by native speakers; the contributor approved all 387 later Gujarati additions on 2026-11-14. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, but the web startup list contains no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. ## The thirteen key languages @@ -34,8 +34,8 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Simplified Chinese (Mandarin) | `zh-hans` | 9,625 rows, 3,735 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`) | all (the untranslated report lists 237 messages without a row for it) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | -| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | -| Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | +| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); not in the web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | +| Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | @@ -101,6 +101,7 @@ font for the web build. | Date | Change | Summary | |---|---|---| +| 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) | | 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback and a glyph-coverage filter; status and error messages not yet translated; native review pending | diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..ccbe5eb0e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -632,6 +632,11 @@ of `appearance.setItem`, `anchor` of `path.removeAnchor` and `addon.pen.removePo value such as `"3"`, `2.5`, `-1` or `true` with `` `index` must be a whole number ``, naming the key, and reports a key left out or null as missing (such as `` missing integer `index` ``). An optional one, such as `subpath`, keeps its default when left out or null; `appearance.setActiveItem` reads a null `index` as clearing the active item. +`file.new` refuses a number given for `artboards`, `artboardLayout.columns` or `artboardLayout.rows` that is not a +whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the +default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or +played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of +1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value @@ -642,7 +647,8 @@ Paint values (`fill`, `stroke`) accept `"#rrggbb"`, `"none"`, `[r,g,b]` (0..1), or a full `paint.setFill` params object (`{"gradient": …}`, `{"swatch": "name"}`). A color read this way (a fill or stroke color, a swatch's, an artboard's or new type's color, and the other colors commands read in these forms) that is given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without -the `#`) is an error and changes nothing, as VectorCraft's own rule. The `color` of Drop Shadow, Inner Glow, Outer Glow +the `#`) is an error and changes nothing, as VectorCraft's own rule. So is a color with a component too large to store +as a 32-bit float, such as `{"c": 1e300, "m": 0, "y": 0, "k": 0}`. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color is read differently and takes `#rrggbbaa`, as described below. For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new-art appearance](#new-art). Both also style the new object in the same call: `dash` (lengths, or null for solid), `cap` @@ -821,7 +827,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | -| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | +| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -985,6 +991,8 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a `item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. +An `appearance.setActiveItem` call made outside a drag's preview keeps its selected row, including an explicit +`index: null`, when the preview is replaced or canceled. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint @@ -1347,7 +1355,7 @@ a script does the same with those commands. SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}}`: `styling` (`presentation`, `style`, `entities`, `css`), `outlineText`, `images` (`embed`, or `link`: embedded images are written next to the SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`, -`responsive`, `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG +`responsive`, `units` (`px`, `pt`, `mm`, `cm` or `in`: overrides the document unit for `width` and `height`; omit to retain the document unit, explicit null is rejected; `px` means bare numbers, the `viewBox` stays in points; ignored with `responsive`), `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG reopens as the full document), `metadata` and `fewerTspans` (one `<tspan>` per line of type). Unknown keys inside `svg` are rejected; `run_command document.formats` lists every option with its default. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1` (ISO 8859-1, other characters as `&#x…;` references); `document.serialize` still answers `text`, plus `dataBase64` @@ -2231,9 +2239,10 @@ in a replayed journal or action too, and nothing changes. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color must be one the effect can read: a hex color (`#rrggbb`, `#rgb` or `#rrggbbaa`, with or without the `#`), `black`, `white`, `red`, `green` or `blue`, `[r, g, b]` -(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`). -`effect.apply` and `effect.setParams` refuse any other value themselves (where the parameter check runs first, a number -or a boolean is refused as not a string), so the app's effect dialogs and Appearance panel, a step of +(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`), with no +number too large to store as a 32-bit float (`[1e300, 0, 0]` is refused). `effect.apply` and `effect.setParams` +refuse any other value themselves (where the parameter check runs first, a number or a boolean is refused as not a +string), so the app's effect dialogs and Appearance panel, a step of `command.batch` and a replayed journal get the same error, and the document and its undo history stay as they were: ```json @@ -2520,7 +2529,7 @@ The transform, Align, Object Properties and Live Shape Properties commands refus that is not true or false with `` `strokes` must be true or false ``, naming the key, and leave the document and its undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `objects` and `typeAreas` in `object.transform`, `object.move`, `object.nudge`, `object.rotate`, `object.scale`, `object.reflect`, `object.shear`, -`object.transformAgain` and `object.setBounds`; `anchors`, `releaseOutside` and `drawBehind` in `object.transform`; `big` in `object.nudge`; +`object.transformAgain` and `object.setBounds`; `anchors`, `releaseOutside` and `drawBehind` in `object.transform`; `big` and `fine` in `object.nudge`; `absolute` in `object.rotate`; `proportional` in `object.setBounds`; `patterns` in `object.align`, `object.distribute` and `object.distributeSpacing`; `visible`, `locked`, `isolate` and `knockoutShape` in `object.setProps`; and `invertPie`, `makeSidesEqual`, `relativeRadii`, `strokes` and `patterns` in `object.setLiveShape`. A null is read as a @@ -2719,9 +2728,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects, syntax and directives, such as `$`, `alert`, `UnitValue`, `reflect`, the XML object and E4X, `#target` and - `#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` - (features only the reference app has: palettes, BridgeTalk, sockets, native code, XMP, operator overloading, - actions and `selectTool`). + `#targetengine`), `dom` (the reference app's document model, `app.selectTool` included), `files`, `menuCommands`, + `dialogs`, and `hostOnly` (features only the reference app has: palettes, BridgeTalk, sockets, native code, XMP, + operator overloading and actions). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. @@ -2745,9 +2754,12 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File - object; a document's `exportVariables` counts too; the same objects left out are not counted for the File-only - functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, - which a Folder object does not have), `filesOpened` (files opened in other apps), `network`, + object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`, + `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not + have; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so do `print` called on + `app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a + variable that holds one of them, and `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given + it saves the document to its file), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2932,7 +2944,7 @@ through `$`: describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`, `app.redraw()`, `app.undo()`, `app.redo()`, - `app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing + `app.getIsFileOpen(path)`, `app.selectTool(name)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing anything. `app.undo()` and `app.redo()` run `edit.undo` and `edit.redo` in the active document and reach only the steps the run made; with no such step they change nothing, and with no document open they throw `No active document` (VectorCraft's own rules). After a run that succeeds, each document that was open @@ -2954,11 +2966,19 @@ through `$`: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level `var selection = ...` does the same and does not make a variable of the script. An assignment to `documents` leaves its value unchanged. Outside strict mode the assignment is ignored, and in strict mode code - (`'use strict'`) or with `#strict on` it throws a `TypeError`. `app.documents` + (`'use strict'`) or with `#strict on` it throws a `TypeError`. `selectTool` + (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942) takes a tool's id + (`pen`), its label (`Pen Tool`) or a tool name in the form that thread lists, returns `true`, and makes the tool it + names the current tool when the run ends without an error; the tool chosen last in a run is the one that counts, + and a run that fails leaves the tool as it was. A name no tool has throws `No tool is named "<name>"`, a name that + is not a string throws a `TypeError`, and a name of more than 4,096 bytes throws a `RangeError`. Which tool each + name in that thread chooses is VectorCraft's own reading; names with no VectorCraft tool throw. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, - which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of - columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol` and the number + of columns for `GridByRow` and `RLGridByRow`; `Row`, `RLRow` and `Column` put the artboards in one row or column and + do not use it; a supplied value must still be a whole number from 1 to `numArtBoards`, which is 1 when omitted, or + `add` throws a `RangeError`), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` @@ -2978,7 +2998,10 @@ through `$`: profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it that cannot be used, for example) goes to the Script Console as a line `addDocument: <warning>`. A `previewMode` of `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. - `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + `showOptionsDialog` true throws `Dialog unavailable` with no document made. `addDocumentNoUI(startupPreset)` + makes the document `addDocument(startupPreset)` makes and ignores any further arguments. A `DocumentPreset` kept + from an earlier run (with `#targetengine`) throws a `TypeError` when its settings are read or assigned and when its `typename` + or `toString()` is read. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems`, `selection` and `views`. `views` (https://ai-scripting.docsforadobe.dev/jsobjref/Views/) lists each window, tab, or tiled pane the desktop app has drawn for the document, in view-number order. Each view @@ -3010,18 +3033,26 @@ through `$`: object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` - (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs - `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is already in + the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` on the + copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the + object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception + is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the + document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of + another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such - an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the value the object already has, which + an object throws `Cannot edit` too. `zOrder()` that would leave the object where it is runs no command: bringing + forward the topmost art of a layer whose ruler guides are above it, sending backward the lowest object above a + clipping path, or any method on the clipping path itself. The one exception is `opacity` or `blendingMode` given the value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity or blend mode, that value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an object that is hidden or locked itself takes `hidden`, `locked`, `opacity` and `blendingMode` (VectorCraft's own rule). Position, @@ -3081,7 +3112,9 @@ through `$`: nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, - letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + letter case is ignored and `\` matches `/`) and does not resolve the path it is given. On Windows every path is a + Windows path; on macOS and Linux only a path that starts with a drive letter is, and in the others `\` is a + character of a file name. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the @@ -3096,6 +3129,164 @@ through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves that this page does not describe are not defined yet and read as `undefined`. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. + When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's + file and saved state unchanged. + `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. + `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). + `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the + format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, + https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); + without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and + `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and + `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`; + `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`, + `saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to + `ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF. + As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an + empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is + true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the + document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). + `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` + and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, + https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), + with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to + 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with + `pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files. + `app.open` rejects a file over 128 MiB before reading it. + Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`; + explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, + `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as + `"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`, + `CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`, + `MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`, + `PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and + `SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A + path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written + or opened. + VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the + command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open + document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is + read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` + and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the + files a command reads or writes besides the one named, such as an SVG's linked files, are + read and written only where the script's folders allow. `userInteractionLevel` does not change what a command + does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the + visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and + when the script's folders refuse one of those files, none of them is written; a write that fails once the + first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws + an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and + `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default + keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in + preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and + `[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes + a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range + (every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its + artboards to `<name>-<artboard name>.ai`, and an EPS range goes to `useArtboards`, which writes + `<name>_<artboard name>.eps` for each of two or more artboards beside the file at the path, and for one artboard + writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS + `artboardRange` is not checked against the document's artboards, but one that is not written as a range of + artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's + file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw + `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved + without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an + undo step. Assigning its current value runs no command and adds no journal entry. + With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; + `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document + was last saved in and after the same write-access check of the path as `saveAs`, and throws an error + and leaves the document open when the document has no file (a converted or recovered document included) or when + the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several + artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with + `useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other + than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve + Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not + refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with + `useArtboards: false`, and the SVG save still refuses a range that selects several artboards. + `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot + show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that + `saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name + (`saveAs: …`). +- `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the + document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings + stay as they are, and `print` adds no undo step + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). + `options` is a `new PrintOptions()`, whose `jobOptions`, `colorManagementOptions`, `colorSeparationOptions`, + `coordinateOptions`, `flattenerOptions`, `fontOptions`, `pageMarksOptions`, `paperOptions` and `postScriptOptions` + are `new PrintJobOptions()`, `new PrintColorManagementOptions()`, `new PrintColorSeparationOptions()`, + `new PrintCoordinateOptions()`, `new PrintFlattenerOptions()`, `new PrintFontOptions()`, + `new PrintPageMarksOptions()`, `new PrintPaperOptions()` and `new PrintPostScriptOptions()` + (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ and the pages beside it). Each property reads as + its help page's default until it is assigned, and a `PrintOptions` holds its option objects by reference, so a change + made after the assignment is printed. `print` maps `printPreset` (a print preset's name) and `flattenerPreset`; + `copies` (1 to 999), `collate`, `reversePages`, `designation`, `printAllArtboards`, `artboardRange`, + `printAsBitmap` and `file` of the job; `colorProfileMode` (`SOURCEPROFILE` and `CUSTOMPROFILE`), `intent` and + `name` (an RGB or CMYK profile) of color management; `colorSeparationMode` (`COMPOSITE` and + `HOSTBASEDSEPARATION`), `convertSpotColors` and `overPrintBlack`; `emulsion`, `fitToPage`, `horizontalScale` and + `verticalScale` (1 to 1000), `orientation`, `position` and `tiling`; `overprint` of the flattener; `colorBars`, + `pageInfoMarks`, `registrationMarks`, `trimMarks`, `pageMarksType` and `trimMarksWeight`; `name`, `width`, + `height` and `transverse` of the paper; and `negativePrinting` and `postScriptLevel` (`PSLEVEL2` and `PSLEVEL3`). + `app.printPresetsList` gives the print presets' names, `[Default]` first, and `app.PPDFileList` is empty. + The enumerations `PrintColorProfile`, `PrintColorIntent`, `PrintColorSeparationMode`, `PrintOrientation`, + `PrintPosition`, `PrintTiling`, `PrintArtworkDesignation`, `PrintingBounds`, `PrintFontDownloadMode`, + `FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold + strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file` + names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is + assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension, and + `printerName` does not apply. Without a file, `print` prints to the + printer `printerName` names, or to the system's default printer when it is `""` or not assigned + (https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). The name must be exactly the name of a printer the + app listed for the run, or `print` throws `PrintOptions.printerName names no installed printer`; with no default + printer it throws `There is no default printer`. `print` composes the job as a print-ready PDF when it is called + and sends nothing while the run goes on. When the run ends and its changes are kept, the app asks before it sends + the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). The dialog does not open + while a text field or text being typed on the canvas has the keyboard; it opens once neither does. The jobs are + sent only after the person at the keyboard clicks its Print button, or presses Space once Tab has moved the focus to + it: the button takes no click for the first second after the dialog appears (VectorCraft's own value), and Enter + does not print. `ui.dialog.set` refuses `answer: "print"`, `ui.dialog.confirm` is refused unless `answer` is + `"cancel"`, and a Print that synthetic input gives is refused and the dialog opens again. Cancel, Escape, + `ui.dialog.cancel` and `answer: "cancel"` drop the jobs and keep the run's changes. A run that fails or is stopped sends + nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none + when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and + none while an earlier run's jobs wait for an answer. The pages are counted from the art as it prints, artboard + backgrounds and placed files included, before the job is composed. A job for a printer is a PDF, so `postScriptLevel` with no + file throws. Where the app lists no printers for scripts (the web build, and MCP or the command line without the app), + `print` with no file throws `Printing to a printer is not available here`. `app.printerList` gives a `Printer` for + each printer the app listed for the run, at most 256, leaving out names longer than 512 bytes or with a control + character; when the system's default printer comes after the first 256, it takes the last place + (https://ai-scripting.docsforadobe.dev/jsobjref/Application/, + https://ai-scripting.docsforadobe.dev/jsobjref/Printer/). Its `name` is read-only and its `printerInfo` throws an + error that says it is not available yet. With no document open, `app.printerList` throws `Application.printerList + needs an open document`, as the Printer help page describes, and where the app lists no printers for scripts it + throws `Application.printerList is not available here`. A printer name is only compared with the listed names: it + is never read as a path, a URL or a command. `fitToPage` set to true wins over the scale factors and the tiling + mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard + prints. With `printAllArtboards` not assigned, an assigned `artboardRange` replaces the range of the settings + `print` starts from, which prints when those settings print a range. `print` starts from the preset's settings + when `printPreset` is assigned, otherwise from the document's saved settings. When those settings ignore the + artboards, an assigned `printArea` prints the artboards an assigned `artboardRange` names, or each artboard without + a range. With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings + `print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an + artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset` + is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any + case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` + and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or + a control character (also at either end), throws too, and each checked name is sent without the spaces around it. + `PPDName` takes only `""`. A listed option that is not mapped, or a value that is not mapped such as + `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000 with `fitToPage` not true, + throws an error that says it is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is + out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a + path given as a string all throw. A run makes at most 256 option objects. Each warning `file.print` gives goes to + the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or + `print.*`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new @@ -3173,8 +3364,9 @@ through `$`: `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path - that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing - changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws + `Cannot edit` with nothing changed, and `pathItems.removeAll()` when any path is on a locked artboard throws + `cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops are not available yet. @@ -3643,7 +3835,8 @@ In the app, a script past the growth limit stops at a question to continue or to with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with `unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In -the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The +the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`, with +`prints`, the number of jobs the run prepared for a printer, when it prepared any. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the script supplied (a value it threw, or an error it made or whose name or message it changed) and `built-in` for the @@ -4406,8 +4599,9 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing. are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a -boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, -also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. +boolean or `null`. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps +it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean or `null` +is rejected. `null` for `guides`, `keepEmpty` or `keepJoined` counts as leaving the key out. Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as `path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected (the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected @@ -4415,7 +4609,7 @@ whole, as `path.removeAnchors` leaves it, so the next Delete removes the whole p cut there, and their selected anchors stay in the path, as with `keepJoined: false`; and objects selected whole are deleted, in the same undo step. `keepJoined` defaults to the `deleteKeepsPathsJoined` preference, and the value used joins the journal entry; a saved step without it opens the paths, as it did when it was recorded. With `ids`, `keepJoined` has no -effect. A `keepJoined` value that is not a boolean is an error, with or without `ids`. +effect. A `keepJoined` value that is not a boolean or `null` is an error, with or without `ids`. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's @@ -4690,7 +4884,7 @@ shows no notice. ## Navigator panel options -The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), +The Navigator panel menu's Panel Options… opens the `ui.navigatorPanelOptions` dialog (fields `color`, `solidDashes`), and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → `{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. @@ -5083,8 +5277,9 @@ already walks Image Trace. Short agent entry points: of it in one undo step; with `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or locked, and the result's `id` is null; a `keepArt` other than true or false is an error; art that holds an instance of the symbol (opacity masks included), directly or through the art of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it - is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged - off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held), + is chosen with Shift held, and the panel sends `symbol.update` with the dragged art's `ids` when art dragged + off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held, with `keepArt: true` when Shift + is held too), `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the @@ -5280,7 +5475,10 @@ already walks Image Trace. Short agent entry points: `brush.new` or `brush.options` without a `key` takes the color that the art's fills and strokes use most (on a tie, the one found first), or black when they use no solid color. `brush.options` changes only the fields of `colorization` and of an art brush's `scale` that `params` gives, so `{colorization: {method: "hueShift"}}` keeps a - Hue Shift brush's key. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the + Hue Shift brush's key. A `brush.options` whose `params` and `newName` leave the brush as it is, and a + `brush.apply` of the current brush whose paths' top strokes already have the brush, paint, a width above 0 and no + settings of their own, do not change the document or its revision and record no undo step. `brush.apply` clears the own settings + (`brush.objectOptions`) of each path's top stroke, and clearing them is one undo step; lower strokes keep theirs. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the default, leaves every copy's colors as the colorization gives them) turns the hue of each copy's solid fills and strokes, its type's characters included, by that copy's own amount between minus and plus that many degrees. The turn comes after the colorization: with None it turns the art's own colors, with Tints and Tints and Shades the @@ -5862,7 +6060,7 @@ already walks Image Trace. Short agent entry points: next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection. Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset - Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`, + Actions is disabled while an action records or plays; it opens an `actionsQuestion` question (fields `message`, `detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing. `ui.actionSet.clear {ids?: [id]}` is Clear Actions, and returns `{cleared}`, the number of sets deleted. It deletes every set in the panel with its actions, the built-in Default Actions set included, so no set is current or @@ -5964,7 +6162,9 @@ already walks Image Trace. Short agent entry points: When `livePaint.gapOptions` or `livePaint.merge` cuts an edge into pieces, each piece takes the edge's paint, with its rows fitted to its part of the edge in the same way. A face or edge given no such row has one unpainted row. Rows that do not draw stay with the stored sources, which `livePaint.release` returns unchanged. The source's object effects and the strokes' pen pressure are not carried. - Expand keeps those face fills. + Expand keeps those face fills. Make, Merge and Gap Options stop with an error and leave the art unchanged when the + paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where + they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when Gap Detection is on. `livePaint.expand` keeps each face and edge that draws, with all its fill and stroke rows: it is shown, its opacity is above 0, and a fill or stroke row is shown, has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top. A painted lower row under an unpainted top row keeps the part; a part whose only painted @@ -5988,7 +6188,9 @@ already walks Image Trace. Short agent entry points: when another merged group has it on. When Gap Detection is off in every merged group, it stays off. The Gap Options dialog (`ui.livePaintGapOptions`) takes `color` as `#rrggbb` or a layer color's name; its OK gives an error for a `color` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. With Preview on, a - `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. + `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. When a + preview fails, the status bar shows the error, the groups go back to how they were, and the dialog stops drawing its preview of the gaps. View › Show Live Paint Gaps still draws the restored + groups' own gaps. `view.livePaintGaps` (View › Show Live Paint Gaps, or Hide Live Paint Gaps while it is on) turns the drawing of those gaps on or off. While it is on and edges show, the canvas draws the gaps of each selected Live Paint group in that group's Gap Preview Color. The reply is the new state (`true` when on). @@ -7565,8 +7767,10 @@ Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `preci whatever the options are then. Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight line encloses no area and does not change the result's shape. When a selected object is or holds such a path, the reply's `warning` says so and names Object › Path › Outline Stroke. When such a path leaves the result empty (Intersect, a line -at the back in Minus Front, or a line in front in Minus Back), the error says so too. - +at the back in Minus Front, or a line in front in Minus Back), the error says so too. Divide with open paths among +the objects stops with an error and leaves the art unchanged when the paths are too many or too complex to map. +This happens when the paths Divide maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where +they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. ```json {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} ``` @@ -7743,14 +7947,14 @@ and `layerRows`, the rows highlighted in the panel. `object.setProps` return an error when they would give either name to another path directly in the group, and a path pasted directly into the group under either name loses its name. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer - {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, + {sublayer?}` open Layer Options (dialog `ui.layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; for existing rows, unchanged approval adds no undo step; an edit is one undo step. Existing rows keep their stored names unless Name is edited or explicitly set through `ui.dialog.set`, so generated labels remain automatic. `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer; in isolation mode `ui.newLayer` for a layer that would be outside the isolated art is an error, OK in the dialog checks again and returns the same error, - and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: + and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`ui.layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas @@ -8566,9 +8770,12 @@ A path with only lone anchors selected, and every path with `wholePaths: true`, {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} ``` -In the desktop app, Object › Path › Simplify opens the slider (`ui.menuDialog {command: "object.path.simplify"}`, -dialog `simplifySlider` with field `level`) at the Auto-Simplify level for the selection and previews the result until -`ui.dialog.confirm`. `ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` +In the desktop app, unless retained settings select the Simplify dialog (see below), Object › Path › Simplify opens a +canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result. +Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` lists +the popover as dialog `simplifySlider` with field `level`. `ui.dialog.set` moves the slider and refuses a level outside +0..100, `ui.dialog.confirm` keeps the result as Enter does, and `ui.dialog.cancel` restores the paths as Escape does. +`ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. @@ -8654,9 +8861,11 @@ are VectorCraft's own. In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the -slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the -Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open -slider back to the Auto-Smooth level. +canvas popover (`ui.menuDialog {command: "object.path.smooth"}`) with a slider for `level` (0..100) at the +Auto-Smooth level. The canvas previews the result. Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; +Escape restores the paths. `ui.inspect` lists the popover as dialog `smoothSlider` with field `level`. `ui.dialog.set` +moves the slider and refuses a level outside 0..100, `ui.dialog.confirm` keeps the result as Enter does, and +`ui.dialog.cancel` restores the paths as Escape does. `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. ## Circle through two or three points @@ -8835,16 +9044,28 @@ path's last point, drawn with the tool's `action` option: Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between switches to the next action: Line, Continuous Arc, Sharp Corner Arc, and back to Line. C flips the last piece, while it is a sharp-corner arc, to the other side of its chord. `[` and `]` make the arc size 15° smaller or larger, for the last sharp-corner arc and the -arcs after it. During a drag, C and `[` `]` change the sharp-corner arc being dragged, and Alt switches its action. A -dragged piece ends where the press is let go. A click on the first point closes the path, and a click on an end of an -open path goes on drawing from that end. Escape or Enter ends the path, and so does an edit made to it by another -command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit +arcs after it, as `tool.quickPen.arcSmaller {}` and `tool.quickPen.arcLarger {}` do (each first finishes any pending +tool edit, then returns false, changing nothing more, when the Quick Pen tool is not active or the step would leave 1° to +359°). `tool.quickPen.arcSmaller` and `tool.quickPen.arcLarger` run in the desktop app (`--connect`). Ctrl with a +scroll on a touchpad over the canvas (the Control key on macOS too) changes the arc size as well, as +[Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) +lists: the touchpad makes one step for each wheel line of its motion, and motion that goes on after the fingers lift +makes none. A mouse wheel turned with Ctrl over the canvas does the same, one step for each net whole wheel line +reported by the canvas framework, with at least one step for a nonzero share. The framework sums events within a +frame, so opposite notches cancel and their order is unavailable. Up makes the arc size larger and down smaller. +Sideways motion makes no step, except when Ctrl on Windows or Linux makes the framework report it as zoom motion. +The view does not zoom or scroll for the rest of that wheel turn. During a drag, +C, `[` `]` and the wheel change the sharp-corner arc being +dragged, and Alt switches its action. A dragged piece ends where the press is let go. A click on the first point +closes the path, and a click on an end of an open path goes on drawing from that end. Escape or Enter ends the path, +and so does an edit made to it by another command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit stays, and the piece stays as last shown. With the `realTimeDrawing` preference off, a press during which another command edits the document adds no piece, and the edit stays. The path's points show as circles without handles, and a preview shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step, together with the flips and size changes made during its drag, and each flip or size change made between presses is one undo step. The -arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` do during a drag and Enter ending the -path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences +arc size of 180°, its 15° steps, the side an arc bulges to, what C, `[` `]` and the wheel do during a drag, Enter +ending the path, the mouse wheel changing the arc size, and the wheel's step per net wheel line and its direction are +VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a protractor around the arc's @@ -10504,7 +10725,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), @@ -10535,7 +10756,9 @@ document. With no document open they fail with "no document open". `document.act the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and -remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current +remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as +having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs +it. `file.close {index}` on a document other than the current one leaves the current document current, and its tool keeps its state; closing the current document makes the document in the next tab current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. @@ -10678,13 +10901,17 @@ preferences (VectorCraft's own place and form). A category without a file has th defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts with the defaults. -- `file.newProfiles` lists `{profiles: [{name, customized?, path?}], folder?}`. `customized` is true when the category - has a file. A request whose read roots leave out the folder gets neither `customized` nor `path`. +- `file.newProfiles` lists `{profiles: [{name, customized?, unusable?, path?}], folder?}`. `customized` is true when the + category has a file. `unusable` is `"not a plain file"` when that file is a link or a folder: `file.new` does not + read it, so new documents of the category get the defaults. Manage Profiles dims its name and turns Edit off; Reset + stays on for a link and is off for a folder. A request whose read roots leave out the folder gets none of + `customized`, `unusable` and `path`. - `file.newProfiles.edit {name}` opens the profile as a document and returns `document.open`'s result. A category without a file gets the shipped profile written first. File › Save keeps the changes, and the next `file.new` reads - them. + them. A profile whose file is a link or a folder gives an error instead. - `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns - `{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open. + `{name, reset}`. `reset` is false when there was no file. A link is removed and the file it leads to is kept; a + folder is not deleted, and the command gives an error. A copy of the profile that is open stays open. - `file.newProfiles.applyDefaults {name}` (Use Profile Defaults, VectorCraft's own command) gives the active document the default fill and stroke and the default font of another profile. The document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] takes the profile's @@ -10992,7 +11219,7 @@ Artboard tool has selected, else its active one. One artboard takes `name`, trim order, `name-1`, `name-2` and so on. A locked artboard is renamed too. An empty name fails with `` `name` must not be empty ``, a name that is not a string fails with `` `name` must be a string ``, and an artboard that is not in the document fails with `no such artboard`. When every artboard already has its new name, the command -records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `renameArtboards` dialog (fields +records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `artboard.rename` dialog (fields `name` and `indices`), and OK with an empty name changes nothing. The Artboards panel's name field runs this command too. Switch Orientation: `artboard.switchOrientation {index? | indices?, scaleArt?, patterns?, lockedAndHidden?}` swaps the width and height of each @@ -11097,7 +11324,7 @@ The reply adds `indices` and `moved`, the number of artboards that moved; with n locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard, and its reply is `{artboards, rows, columns}`; `at` there puts the grid's top-left at `at` too. In the desktop app, the Artboard tool's canvas menu and Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards -panel's menu (Rearrange…), open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the +panel's menu (Rearrange…), open the Rearrange dialog (key `artboard.rearrange` with field `indices`) for the artboards the tool has selected, showing their count. With another tool Rearrange… is off. The panel's Rearrange button stays Rearrange All Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when @@ -11317,6 +11544,10 @@ image `object.rasterize` makes with the same options. {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"rasterize","params":{"useDocumentResolution":false,"resolution":150,"background":"white"}}}} ``` +Color Halftone (`pixelate.colorHalftone`) screens cyan, magenta and yellow ink in RGB mode and also black ink in CMYK +mode. Dot area follows each cell's mean ink coverage. A full-strength dot has a finite radius that fills the cell, +including its corners. + ## Glass textures Glass (`distort.glass`) takes an image file as its surface in `params.textureImage`, as `{path}` or @@ -11855,7 +12086,8 @@ height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all art), `includeBleed` grows each artboard by the document's bleed (a PDF row's page keeps the artboard as its TrimBox and puts the row's `bleed` around it once: the row's own values, zero included, else the document's bleed -when the row sets none and its PDF preset gives none or a bleed of 0), `includeArtboardFill: false` (Include Artboard +when the row sets none and its PDF preset gives none or a bleed of 0; a native, `.ai` or EPS file of an artboard +holds the grown artboard with a bleed of 0, so the bleed is not added again when the file is opened), `includeArtboardFill: false` (Include Artboard Fill unchecked) leaves the artboards' background colors out of the files, `pdfs: "single"` (Export PDFs As › Single file) writes the artboards a PDF row exports as the pages of one PDF named after the document (it is refused with `assets`, `layers` or `selection: "each"`, whose files each hold one item's art), `subfolders` puts each @@ -12490,7 +12722,9 @@ Open Location after Export run these two (sub-folders sort the pictures; `assets folder itself), and its Format Settings… opens Export for Screens on the first row's format settings. `document.exportForScreens {assets: [id…]}` does the same with its own params (the dialog's Assets tab). An asset's crop, and the crop of `export` with `selection: true`, is the bounds the -renderer measures for what the art draws, its effects included. +renderer measures for what the art draws, its effects included. In the panel, Export Settings takes at most half the +panel's height and scrolls on its own, so every format row can be reached in a short panel while Export and the footer +bar stay in place. ```json {"name":"run_command","arguments":{"command":"assets.add","params":{"multiple":true}}} @@ -12906,7 +13140,9 @@ bleed, composite or separations output, graphics and colour management options o `transform` from the document onto the page (pt, y down), the document `area` it prints, its `trim` box on the page and, with copies per sheet, each copy's artboard on the page (`copies`), plus `tiles`, the `inks` of a separation and `warnings`. `file.print {settings?, path?}` writes the job as a print-ready PDF (one page per -sheet, tile, ink and copy); headless it answers `dataBase64`. In the app, `file.print` with no params opens the Print +sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, the job is composed only when it +prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers +`{pages, format}`. In the app, `file.print` with no params opens the Print dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. @@ -13422,7 +13658,12 @@ for near matches; when none passes, the shape stays an outline. Glyphs fused int or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one -comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. Those 256 can +all be glyphs of other fonts drawn alike (a period or a dot): a shape matched whole, whose matches are all near +matches in other fonts than that of the line before it, is also compared with the 256 glyphs of that line's font +closest to it in proportion when it does not join the line, and joins the line when one of them fits. A shape with an +exact match, a shape split into several glyphs, a shape that matches no glyph at all and a shape after an unmatched +shape are not compared again. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes @@ -15469,7 +15710,7 @@ effects keep their colours. ## Vector halftone `object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its -tone (mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the +tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the `warning` that Flatten Transparency gives: @@ -15725,10 +15966,12 @@ a flare into a plain group of its parts. The document saves a flare's settings. The Shape Builder tool's options are its Shape Builder Tool Options (dialog `shapeBuilderOptions`): `openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; a path counts as filled when any of its fill rows is shown, painted and above 0% opacity, whichever row is on top; off: it cuts regions -as an unfilled path does), `pickColorFrom` (`artwork`, the default: a merged shape takes the appearance, opacity and -blending mode of the front-most selected object under the drag's first point, else of the one under its last point, -else of the front-most selected object; `swatches`: the current fill, and the Left and Right arrow keys without -Shift, Alt or Cmd/Ctrl step the current fill through the document's color swatches), `cursorSwatchPreview` (off; with `swatches`, chips above the +as an unfilled path does), `pickColorFrom` (`swatches`, the default: a merged shape fills with the current fill, and +the Left and Right arrow keys without Shift, Alt or Cmd/Ctrl step the current fill through the document's color +swatches; `artwork`: a merged shape takes the appearance, opacity and blending mode of the front-most selected object +under the drag's first point, else of the one under its last point, else of the front-most selected object; a +`pickColorFrom` saved with the preferences is kept, except that preferences saved by an earlier version, without +`toolSettingsVersion`, read a saved `artwork` as `swatches` once; preferences saved without one take `swatches`), `cursorSwatchPreview` (off; with `swatches`, chips above the pointer show the current fill and the swatches before and after it), `selection` (`freeform`, the default, or `straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode, @@ -16054,8 +16297,8 @@ edge also lands only when it ends within a quarter cell of a gridline: a horizon edge on its own axis, and a 45° move lands the edge on the axis whose nonzero correction is smaller. When no edge on those axes is that close, the move does not snap. A perpendicular move does not snap. `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the -grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt -copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. +grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, +Ctrl/Cmd ÷10 (`fine`), Shift+Ctrl/Cmd one increment, Alt copies); Snap to Grid doesn't pull a nudge onto the gridlines. Object › Transform › Transform Again repeats the last perspective move or scale in plane space. ```json {"name":"pointer_gesture","arguments":{"tool":"perspectiveSelection","events":[{"kind":"down","x":480,"y":410},{"kind":"drag","x":470,"y":405}]}} @@ -16067,8 +16310,8 @@ copies). Object › Transform › Transform Again repeats the last perspective m The perspective, width point, Liquify and Puppet Warp commands refuse a string, a number or another value that is not true or false with `` `copy` must be true or false ``, naming the key, and leave the document and its undo history as -they were: `copy`, `perpendicular` and `snap` in `perspective.move`; `copy` in `perspective.transform`; `big` and -`copy` in `perspective.nudge`; `snap` in `perspective.draw`; `reproject` in `perspective.grid.set`; `visible` in +they were: `copy`, `perpendicular` and `snap` in `perspective.move`; `copy` in `perspective.transform`; `big`, `fine` +and `copy` in `perspective.nudge`; `snap` in `perspective.draw`; `reproject` in `perspective.grid.set`; `visible` in `perspective.grid.show`; `adjustAdjoining` in `stroke.widthPoint.set`; `usePressure`, `simplifyOn`, `affectAnchors`, `affectIn` and `affectOut` in `object.liquify`, with any `tool`; and `rest` in `object.puppetWarp`. A null is read as a key left out. @@ -16828,7 +17071,7 @@ Commands: With `fit`, every run between corners and ends holds a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path with no corner holds whole periods); otherwise the lengths are exact and the last piece of each run is what is left. The pieces are selected; more than 100,000 is refused. → `{ids, dashes}`. - Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, kind `divideDashes`) whose fields are these + Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, key `addon.pathtools.divideDashes`) whose fields are these parameters, with Preview. - `addon.pathtools.expandDashes {ids?}` turns the dashed stroke of each path and compound path under `ids` (default: the selection) into separate open paths, one per dash, as one undo step (Object › Plug-ins › Path Precision Tools › @@ -16841,9 +17084,10 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. -- `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection; - paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › - Plug-ins › Path Precision Tools › Smooth Bridge…). Two circles become one closed outline that goes around each circle +- `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection, + with a group other than a clipping group giving the objects inside it at any depth, which must all be circles; paths + whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › + Plug-ins › Path Precision Tools › Common Tangents… with External and Curved). Two circles become one closed outline that goes around each circle on its side away from the other and along two concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by default): a larger radius makes a wider, gentler bridge. `gap` (0 to 1,000 @@ -16851,12 +17095,19 @@ Commands: circle of the smaller circle's size about the arc's center. For equal circles that gap apart, that center is where a third circle the gap from both would sit, as in a triangular grid, so the channels around an empty place in such a grid are one width; in a square grid they are not. Giving both `radius` and `gap` is an error. Overlapping and - touching circles are joined at every radius. One circle inside the other is an error, and so are circles too far apart + touching circles are joined at every radius. An object that is not a circle is an error that says why: an ellipse whose + width and height differ, a compound path, an object that is hidden or locked, or another object. More than 2,000 + objects (with each group other than a clipping group counted as the objects inside it, and a clipping group as one + object, which is not a circle) are refused as more than 2,000 circles before any of them is + checked, so that error does not say which object is not a circle. One circle inside the + other is an error, and so are circles too far apart for the radius or gap: the arcs would not reach both circles, or would cross before they do. The error suggests a larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles stay. The outline is selected. Two circles are bridged however far apart - their outlines are; `reach` does not apply to them. + their outlines are; `reach` does not apply to them. When outlines replace circles (with any number of circles), a group + or compound path that the circles leave with nothing in it is removed, and so is each group above it left empty in + turn; layers stay. With three or more circles, every two whose outlines are at most `reach` apart (0 to 10,000 pt, 10 by default; overlapping ones included) are bridged the same way, and the bridges that connect are united into one shape each, which can have holes where bridges enclose space; holes smaller than 1% of the smallest circle's area are filled. A @@ -16866,9 +17117,11 @@ Commands: other stays as it is. The shapes and the circles left as they are are selected. It is an error when any pair within reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: - the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog - (`ui.menuDialog {command}`, kind `smoothBridge`) with Constant Gap (a Gap field in place of the Radius field in - percent), Reach (unavailable with two circles selected), Keep Originals and Preview. + the shapes and the circles left as they are, with `id` as well for two circles. Opening `addon.pathtools.bridge` + from the menu dialog (`ui.menuDialog {command}`) opens Common Tangents' dialog (key + `addon.pathtools.commonTangents`) with External and Curved on, described under + `addon.pathtools.commonTangents`. No menu item runs `addon.pathtools.bridge`, and the command palette and Keyboard + Shortcuts leave it out; scripts and actions still run it. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` @@ -16887,7 +17140,7 @@ Commands: circles), when `circle` is past the last one, when `ids` names an object twice, when the shapes lie at one point or are too small for the radius, above 2,000 segments in all, and when the search for other shapes goes past its limits. → `{ids, found}` (`found`: how many circles touch the shapes). Tangent Circle… opens a dialog - (`ui.menuDialog {command}`, kind `tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a + (`ui.menuDialog {command}`, key `addon.pathtools.tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a Circle menu (All, or one circle by number, as many as the last preview found) and Preview, which starts on. - `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and @@ -16969,7 +17222,7 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). -- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed +- `addon.pathtools.commonTangents {tangents?, centerline?, connect?, curved?, radius?, gap?, reach?, keepOriginals?, ids?}` adds the common tangent lines of two convex closed paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or @@ -16994,9 +17247,19 @@ Commands: runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are stroked with the current stroke color and weight (black when the stroke is None), have no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of the kind asked for, - nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with - Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, - centerline, warning?}` (`centerline`: the centerline's id, or null). + nothing changes, and the result's `warning` says why. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). With `connect: true` the two tangents of each kind become one closed + path instead of two lines, joined by the chords between where they touch each path (two internal tangents make a + crossed shape, and a point's two lines make a triangle); a kind with one tangent stays a line, and the centerline + stays a line. With `curved: true` it joins the selected circles into one outline along concave arcs instead, as + `addon.pathtools.bridge` does, taking that command's `radius` or `gap`, `reach`, `keepOriginals` and `ids`, and + the result is that command's. `tangents` other than `external`, `centerline` and `connect: false` with `curved` are + an error, and so are `radius`, `gap`, `reach` and `keepOriginals` without it. Common Tangents… opens a dialog with + Tangents, Centerline and Connect tangents; with External it also shows Straight and Curved (Straight by default) and + the bridge's options: Constant Gap (a Gap field in place of the Radius field in percent), Reach (unavailable when the + selection, a selected group's objects counted, holds two objects) and Keep Originals, which take input only with + Curved. With Curved, Centerline is unavailable and Connect tangents shows on. Choosing another kind of tangent goes + back to Straight. With a point selected, every Tangents choice gives the same lines. - `addon.pathtools.boundingRectangle {each?, offset?}` draws a live rectangle on the geometric bounding box of the selected objects, strokes and effects left out (Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle…, #6966). `addon.pathtools.boundingCircle {each?, offset?}` draws the smallest live circle that holds the outlines of @@ -17406,6 +17669,35 @@ on the object or on one of its fills or strokes; a group carrying one is selecte `grayImages` (images whose pixels are RGB, CMYK, or grayscale or 1-bit, read from the image's header). It returns the `count` selected. +`addon.color.randomFill {scheme?, swatch?, min?, max?, seed?, ids?}` (Object › Plug-ins › Color Effects › Randomize +Fill Colors…) gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping +groups, a top fill color of its own, picked at random and evenly, as one undo step (none when no fill changes): + +| `scheme` | Each fill becomes | +|---|---| +| `color` (the default) | A color with red, green and blue each at random, in the document's color mode | +| `tint` | A tint of `swatch`, a global or spot color swatch, linked to it, from `min` to `max` percent | +| `gray` | A gray from `min` to `max` percent black | + +`min` and `max` are 0 to 100 (0 and 100 when left out) and go with `tint` and `gray` only; `swatch` goes with `tint` +only and is needed there (a tint swatch gives tints of its base, which must still support tints). The same `seed` (a whole number, 0 when left out), +objects and settings give the same colors. The colors are drawn in the order `ids` lists the objects, a repeated id counting once and an id inside a listed group +taking its color when that group's objects are colored, +so with the ids in another order the same seed can give each object a different color. Compound paths and live compound shapes take one color and keep their members' fills. +An id naming a nested member targets the outermost compound. +Paths, compound paths and live compound shapes with no fill, clipping paths (a compound path that +clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by +the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them +for its next redraw, so after the redraw every mark of the series has that one color. It returns the +`count` of objects whose fill changed. An unknown scheme, `min` or `max` with `color`, `swatch` without `tint`, a +percent outside 0 to 100, `min` above `max`, a missing or process swatch, a tint swatch whose base cannot produce tints and a seed that is not a whole number are +errors, and the document is left as it was. The dialog's seed starts new whenever the document has changed, and its +Swatch choice lists the document's global and spot swatches. + +```json +{"name":"run_command","arguments":{"command":"addon.color.randomFill","params":{"scheme":"tint","swatch":"Ink","min":20,"max":80,"seed":7}}} +``` + ### Selection Tools Selection Tools is a built-in add-on: its commands are `addon.select.*`, and in the desktop app it lives in Object › @@ -17455,6 +17747,31 @@ locked". Select by Link Status… lists every image and placed document with its name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select selects the rows chosen, zooming to them when Zoom to Selection is on (the default). +`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to paths and their selected +anchor points. A path with selected anchor points keeps them. +A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of +the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor +points. A path selected whole stays selected whole and still receives object transforms, including stroke and effect +scaling when enabled. A group or compound path selected whole is replaced by the paths +inside it, each selected whole unless it has an explicit anchor pick. Explicit anchor picks take precedence regardless +of selection order. The command leaves out hidden and locked paths, a Shaper Group's original shapes and, while +guides are locked, paths made into guides. Type, +images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. The command +does not add an undo step. It returns `{changed, count, points}`: `changed` is `false` when the +selection already held only anchor points, `count` is the number of paths left selected and `points` the number of +anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a +`segmentEnds` that is not `true` or `false` (including `null`) is an error, and the selection is left as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog (`ui.menuDialog {command}`, key +`addon.select.editPointsOnly`) with Keep Ends of Selected Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection +back. +After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current +status message. Messages from other commands stay displayed. + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its @@ -17464,7 +17781,7 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope | Parameter | Values (default) | Does | |---|---|---| -| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line` (`circle`) | The dot shape; lines join along a row | +| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes | | `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen | | `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it | | `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other | @@ -17572,7 +17889,8 @@ images and patterns keep their colours. → `{changed, swatches: [the document s Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are `addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured -as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds. +as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds, and Group by Row, which always uses visual bounds +with strokes and vector effects included and raster effects left out (see its row). | Command | Parameters (default) | Does | |---|---|---| @@ -17583,23 +17901,28 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs -(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose +(`ui.menuDialog {command}`; each dialog's `key` is its command id, such as `addon.arrange.grid`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's parameters, with Preview; it opens on the key object when the selection has one, else on the top object, and OK is off while nothing is chosen to match or the source is the key object and there is none. Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order -and Reverse Order. +and Reverse Order. Group by Row… opens one too (`ui.menuDialog {command: "addon.arrange.groupRows"}`), with Group By +(Rows or Columns). Mark Bounds of Each… opens a dialog of the command's parameters with Preview; Length is off unless +Draw is Corner Marks. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}} +{"name":"run_command","arguments":{"command":"addon.arrange.groupRows","params":{"direction":"row"}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} {"name":"run_command","arguments":{"command":"addon.arrange.match","params":{"source":"key","size":"both","rotate":true}}} @@ -17792,7 +18115,7 @@ are skipped as `addon.packaging.setRole` skips them; cut lines and objects witho command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. -Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the +Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, key `addon.packaging.setFoldAngle`) on the angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it as it is typed, as one undo step; canceling the edit restores the lines' angles and leaves no undo step. The Reset button beside it takes their own angles away. @@ -17981,8 +18304,8 @@ A `start` or `end` byte inside a character rounds down to that character's start | `seed` | whole number (0): `random` with the same seed and text gives the same values | | `skipSpaces` | true: spaces and line breaks keep their values and don't count | -→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog kind -`textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own +→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog key +`addon.type.textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own default values, and the seed starts new whenever the document has changed. ```json diff --git a/docs/production-preflight.md b/docs/production-preflight.md index ecc551f0c9..d288416270 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -13,10 +13,11 @@ The panel checks: - **Image Resolution:** effective resolution along both pixel axes at the image's placed size. Print includes the job's page transform, so enlarging the print can lower effective resolution. -Click a finding to select and zoom to the affected artwork. A font finding can select several -objects. A finding inside a symbol, pattern, brush or opacity mask locates its first visible -canvas owner. If some artwork cannot be selected, the status bar reports it; any selectable -objects are still located without unlocking artwork or artboards. **Find Font…**, **Relink…** and +Click a finding to select and zoom to the affected artwork. Right-click a finding or press +Shift+F10 on its focused row for **Select and Zoom** and any available repair action. +A font finding can select several objects. A finding inside a symbol, pattern, brush or opacity +mask locates its first visible canvas owner. If some artwork cannot be selected, the status bar +reports it and the panel still locates any selectable objects. **Find Font…**, **Relink…** and **Update Link** open the existing repair workflows; they do not apply an automatic font substitution or change artwork just by checking it. @@ -77,6 +78,9 @@ WebAssembly Clippy run also encounters existing target-specific lints in unchang (`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and the native Clippy run above pass without source changes for those findings. +The engine preflight tests now live in the `it` test binary. Run them with +`cargo test -p vectorcraft-engine --test it preflight::`. + ### Review follow-up on `main` at `ee60c51fd` The exact-threshold and locked-artboard regressions were first run against the original diff --git a/docs/roadmap.md b/docs/roadmap.md index 971ca6eafa..f669559fd2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,7 +1,7 @@ # Roadmap: milestones and what's next > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -33,8 +33,11 @@ ## Feature submission evidence Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. + +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -192,7 +195,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | @@ -206,8 +209,8 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | -| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | +| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -262,6 +265,8 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | +| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-19 | minor | M14/G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..f39715b827 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3,7 +3,7 @@ Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written. > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -15,6 +15,8 @@ Native saves on Unix flush the destination directory after writing or replacing > > Glyphs update (#5514): Alternates for Current Selection applies a variant's OpenType feature to that letter alone (`salt=2`) so an Arabic word stays joined; Entire Font lists unencoded glyphs. A positional variant no supported feature draws can be applied as a glyph choice (#6084). Entire Font uses the selection's font version and variable axes, and the default cell remains available after an unlisted choice even without GSUB alternates. Only Arabic presentation-form characters insert their joining base letter. Scores and estimates unchanged. > +> SVG physical dimensions update (#5450): explicit SVG Options write width and height in mm, cm, in or pt (#4462), retaining scale independently of coordinate precision, including tiny sizes. Commands accept flat `units` or nested `svg.units`; nested values win and explicit null is rejected. Without an override, export retains the document's units (#864). Responsive omits dimensions; explicit Pixels keeps bare numbers and CSS pixels are 96/in. Scores and estimates unchanged. +> > **File-font integration status (2026-11-19, #4569):** 56 focused integration tests passed, including wrapped carried-font paragraphs and conflicting glyphs through native reopen. Full workspace CI and other hardening paths remain pending. Type core and file-format scores and estimates unchanged. See [file-font ownership evidence](file-format-parity.md#file-font-ownership-hardening-4569). > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). @@ -73,11 +75,15 @@ Script page-item and layer objects become stale after `file.revert`, including w Script appearance and geometry setters reject objects on locked artboards. Assigning the current opacity remains allowed when it changes no graph styling. Position, size and stacking-order setters also reject objects excluded by selection filtering, including locked guide paths. `crates/engine/src/tests/script_dom.rs` covers refused edits, unchanged documents and undo history, and editing a guide after unlocking it. +**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. + +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. @@ -286,11 +292,11 @@ the work list made from it. Deep areas have their own checklists: [UI and intera | 2026-10-22 | minor | PDF import: a gap between glyphs of two sizes reads as a space measured against the smaller size (#3623); mixed-size regression. Scores and hours unchanged. | | 2026-10-21 | minor | PDF import: letter-spaced type keeps its word spaces and gains none between letters; synthetic Tc and glyph-by-glyph regressions. Scores and hours unchanged. | | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | -| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 717 of 719 items wired (99.7%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | -| **Feature depth** (each area scored by behaviour, weighted) | **~75%** | estimated, area table below | +| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~96%** | measured in part: menu tree 815 of 816 items wired (99.9%; only Effect › 3D and Materials › Materials… is a stub), tools 91 of 92 (99%), vector effects 50 of 50 (100%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (Extrude & Bevel, Revolve, Inflate, Rotate) plus 3 of 3 Classic, no base materials or Turntable; blended by the area weights below (presence per area × weight / 105) | +| **Feature depth** (each area scored by behaviour, weighted) | **~79%** | estimated, area table below | | **Ready for real work, mainstream illustrator** | **~65%** (60–70%) | estimated, see [Ready for real work](#ready-for-real-work) | -| **Ready for real work, full Illustrator** (decides the stage) | **~62%** (57–67%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | -| **Ready for real work, essentials user** (core features only, see [Essentials user](#essentials-user)) | **~75%** (70–80%) | estimated | +| **Ready for real work, full Illustrator** (decides the stage) | **~67%** (62–72%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | +| **Ready for real work, essentials user** (core features only, see [Essentials user](#essentials-user)) | **~77%** (72–82%) | estimated | | **Remaining to beta** | **~170–270 h** one agent | estimated, [gaps.md](gaps.md) beta list | | **Remaining to full parity** | **~360–590 h** one agent · ~95–165 h wall clock with 4–6 agents | estimated, sum of the area table + fidelity pass + hardening | @@ -346,49 +352,35 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | -| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | +| Selection, transform & align tools | 6 | 86% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/it/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 88% | Shaper construction widget, Pencil/Pen nuances; Touch Type (#2469), the Dimension tool (#1788) and the Blob Brush options (#2367) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/it/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | +| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, the stylus wheel on native Wayland (it is read under X11 and XWayland, on macOS, on Windows through Wintab and in the web build), more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | -| Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Optical Margin Alignment is done for point and area type and type on a path, right-to-left paragraphs included; remaining: Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | editable ruby text in standard SVG and PDF artwork (written as outlines; see [type-parity.md](type-parity.md)), custom Mojikumi sets and the Mojikumi Settings dialog, Retype from images, Retype panel matching depth and fused glyphs (see [type-parity.md](type-parity.md)), Touch Type along a line for a character with no immediately preceding logical character on the same line in the same direction (movement along the baseline is disabled; baseline shift still works) | 20–28 | estimated; Retype (`type.retype`, exact and tolerance-based outline matches, #4934); No Break suppresses automatic breaks within the marked run (a forced line break still breaks); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them on instances the copy keeps live, within the limits the File formats row lists (fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one), further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides when the embedded document is current and readable); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | +| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep; large images trace with a warning or are downsampled, and images beyond the size and decode limits in `crates/trace/src/raster.rs` are rejected; Auto Color keeps rare distinct colors in coherent regions when the Automatic palette classifies the image as flat artwork) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | +| Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | +| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows from lights after the first and in Classic effects (only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | -| Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on blend spine rows (guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | +| Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | +| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (images with a Warp effect keep it editable when they qualify), and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | -| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | +| Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | -| Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged | +| Automation (Actions, Variables, scripting, batch) | 3 | 80% | script DOM classes for layers, artboards and gradient stops, `#engine` (#1183), Batch option depth (scripting, #9019, Batch, #1938, and image and graph variables are done) | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged; Layers appearance marker uses a hollow diamond and tooltip separate from targeting and selected art (#8710), based on Hassan1305's #8757; focused Layers coverage, runtime validation pending; scores and hours unchanged; Tools toolbar Search entry and retained customization covered in `crates/ui-egui/src/toolbar/tests.rs` (#8758), scores and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | -| **Feature depth** | **105** | **~75%** | | **~250–420** | | +| **Feature depth** | **105** | **~79%** | | **~250–420** | | | Interaction-fidelity pass (every tool's modifiers, cursors, Properties per context) | | | [ui-parity.md](ui-parity.md) | 60–90 | estimated | | Hardening (real-file corpus, cross-platform and browser QA, launch failures, performance budgets) | | | [gaps.md](gaps.md) | 50–80 | estimated; PngSuite fetch integrity and size budgets regression-tested (#1729) | -| **Full parity** | | **~55%** | | **~360–590** | | +| **Full parity** | | **~58%** | | **~360–590** | | -Excluding the generative-AI row (the old table had none), depth is ~76% and the remaining feature work +Excluding the generative-AI row (the old table had none), depth is ~81% and the remaining feature work ~220–360 h. With 4–6 agents on disjoint crates, wall-clock time divides by about 3.5–4 (shared files such as `menus.rs` and the i18n catalogs serialize some work): ~95–165 h to full parity. @@ -407,9 +399,9 @@ review parallelize less and need humans. | Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates | |---|---:|---:|---:|---| -| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (24–40 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem | +| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (24–40 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | +| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | ### Full Illustrator: additive weighted sum over the dimensions @@ -418,17 +410,17 @@ Values are from [By dimension](#by-dimension). | Dimension | Weight | Value | Contribution | |---|---:|---:|---:| -| Features (depth) | 35 | 75% | 26.3 | -| UI/UX fidelity | 15 | 55% | 8.3 | +| Features (depth) | 35 | 79% | 27.8 | +| UI/UX fidelity | 15 | 60% | 9.0 | | File formats | 12 | 75% | 9.0 | -| Stability | 10 | 60% | 6.0 | +| Stability | 10 | 55% | 5.5 | | Performance | 8 | 60% | 4.8 | -| Platforms | 5 | 80% | 4.0 | -| Hardware | 4 | 35% | 1.4 | -| Localization | 4 | 74% | 3.0 | -| Ecosystem and plug-ins | 4 | 15% | 0.6 | +| Platforms | 5 | 82% | 4.1 | +| Hardware | 4 | 45% | 1.8 | +| Localization | 4 | 87% | 3.5 | +| Ecosystem and plug-ins | 4 | 30% | 1.2 | | AI features | 3 | 0% | 0.0 | -| **Ready for real work** | **100** | | **~62%** | +| **Ready for real work** | **100** | | **~67%** | The weights put most of the number on what professionals use daily (features, interaction, files, stability). Generative AI also sits inside the features row at weight 2 of 105, so it is counted slightly twice; that costs @@ -436,11 +428,11 @@ under a point. ### Mainstream illustrator and essentials user -Both start from feature depth over the areas concerned. **Mainstream:** ~83% over 16 areas (weight 83 of 105: +Both start from feature depth over the areas concerned. **Mainstream:** ~86% over 16 areas (weight 83 of 105: selection, drawing, path operations, colour, strokes, appearance, live effects, type core, symbols and blends, layers and artboards, view, guides, file formats, Export for Screens, UI chrome, print). That is discounted ×0.9 for interaction fidelity, ×0.92 for stability on real machines and ×0.92 for Illustrator-file exchange -(83 × 0.9 × 0.92 × 0.92 ≈ 63). The dimensions a typical illustrator rarely hits (plug-in ecosystem, +(86 × 0.9 × 0.92 × 0.92 ≈ 65). The dimensions a typical illustrator rarely hits (plug-in ecosystem, generative AI, pen tilt, languages beyond their own) are left out. **Essentials:** see [Essentials user](#essentials-user). The discounts, with the evidence: @@ -452,8 +444,8 @@ The discounts, with the evidence: #868), guides lost (#779), slower opening (#758), live effects, brushes and symbols as their drawn look (#637). VectorCraft's PDF-compatible `.ai` carries an editing copy of the art (layers, groups, paths, colors, gradients, patterns, images, transparency, opacity masks, clipping, type as text and symbols), with live effects kept only - on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, other objects' effects other than geometry - effects left out, and live objects written as their art; the legacy `.ai` of version 7 it also writes keeps layers, groups and type as text (one + on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports and on images with a Warp effect that qualify, other objects' effects other than geometry + effects left out, and live objects written as their art, except the graphs, envelopes, blends, symbol instances and gradient meshes that qualify (the File formats row and the editing-copy evidence below give the limits); the legacy `.ai` of version 7 it also writes keeps layers, groups and type as text (one artboard per file, no transparency) but hasn't been tested by users yet (#868). That blocks beta (the main-format rule) for people who hand files back to Illustrator users, but it doesn't stop someone opening and reworking their own archive. - **Interaction fidelity (×0.9).** Pen, Direct Selection, smart guides and snapping are deep @@ -488,11 +480,11 @@ Depth here is "does the basic use work", not the area's full score. | Gradients, basic | 4 | 90% | Gradient panel and on-canvas annotator | | Type: point and area text, font, size | 8 | 88% | font menu with previews; Hyphenation… and Justification… options per paragraph (#2310, #2755) | | Align, group, arrange | 6 | 95% | | -| Layers, basic | 4 | 85% | Layers panel rework; selected guide rows keep their highlight (#7344); row context menus offer only Collect for Export | -| Shape Builder | 5 | 70% | beginners lean on it; region detection failed on art of thousands of segments (#937's reproduced case, fixed, and its edge-source grid is bounded in memory; unconfirmed on the reporter's file) | +| Layers, basic | 4 | 90% | Layers panel rework; selected guide rows keep their highlight (#7344); row context menus offer Options, Duplicate, Delete, Lock and Hide Others, Locate and Collect for Export | +| Shape Builder | 5 | 78% | beginners lean on it; region detection failed on art of thousands of segments (#937's reproduced case, fixed, and its edge-source grid is bounded in memory; unconfirmed on the reporter's file) | | Pathfinder | 4 | 95% | exact booleans | | Place images, Image Trace | 4 | 85% | 13 trace presets | -| Export PNG/JPG/SVG/PDF, print | 8 | 92% | Art Optimized supersample closes Asset Export ghost borders (#983 / #1037) | +| Export PNG/JPG/SVG/PDF, print | 8 | 88% | Art Optimized supersample closes Asset Export ghost borders (#983 / #1037); printing crashes on some Windows machines (#8021, #9261) | | Undo and redo | 4 | 100% | unlimited, property-tested | | Zoom, pan, fit | 4 | 95% | | | Artboards, basic | 4 | 88% | | @@ -501,13 +493,14 @@ Depth here is "does the basic use work", not the area's full score. The discounts a beginner actually hits: - **Launch and stability, ×0.93:** fine on macOS, but some Windows machines fail to start (#858, #620, #818). -- **Discoverability and UI clarity, ×0.92:** the layout follows Illustrator's and comes in 11 languages, but - there is no in-app help (Help › VectorCraft Help… is a stub), no Learn panel or tutorials, and a newcomer +- **Discoverability and UI clarity, ×0.95:** the layout follows Illustrator's and comes in 11 languages; + Help › VectorCraft Help… (F1) searches tools, menu commands and tutorials, and Window › Learn has 12 + tutorials, but there are no help articles, and a newcomer meets Illustrator's density without Illustrator's learning material. - **Opening files people send them, ×0.96:** PDF, SVG, images and most `.ai` files open as editable art. Layer-structure problems (#951) matter less to a beginner. -91 × 0.93 × 0.92 × 0.96 ≈ 75: **~75% (70–80%), estimated.** +91 × 0.93 × 0.95 × 0.96 ≈ 77: **~77% (72–82%), estimated.** ### User sentiment (measured 2026-10-10) @@ -531,15 +524,15 @@ what keeps it from beta, not from alpha. | Dimension | % | One agent (h) | Kind | Doc | |---|---:|---:|---|---| -| Features (depth, weighted) | 75% | 220–360 | estimated | this file | -| UI/UX fidelity (look ~80%, interaction ~45%) | 55% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring); held spinner arrows keep stepping (#6307); Vector Halftone Preview keeps the selection box without the dot marks (#6369) | +| Features (depth, weighted) | 79% | 220–360 | estimated | this file | +| UI/UX fidelity (look ~80%, interaction ~50%) | 60% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring); held spinner arrows keep stepping (#6307); Vector Halftone Preview keeps the selection box without the dot marks (#6369) | | File formats | 75% | 15–30 | estimated | [file-format-parity.md](file-format-parity.md) | -| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | -| Localization (the 12 key languages, equally weighted) | 74% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | +| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | +| Localization (the 12 key languages, equally weighted) | 87% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | | Performance | ~60% | 15–25 | estimated (unverified budgets; measured long-path hits, large-selection nudges and text thread filtering) | [gaps.md](gaps.md) | -| Stability | ~60% | 30–50 | estimated | [gaps.md](gaps.md) | -| Platforms (macOS, Windows x64/arm64, Linux, FreeBSD, web) | 80% | 15–25 | estimated | [gaps.md](gaps.md) | -| Ecosystem and plug-ins (scripting, third-party plug-ins) | 15% | 30–60 | estimated | [gaps.md](gaps.md) | +| Stability | ~55% | 30–50 | estimated | [gaps.md](gaps.md) | +| Platforms (macOS, Windows x64/arm64, Linux, FreeBSD, web) | 82% | 15–25 | estimated | [gaps.md](gaps.md) | +| Ecosystem and plug-ins (scripting, third-party plug-ins) | 30% | 30–60 | estimated | [gaps.md](gaps.md) | | AI features (generative) | 0% | 30–60 (+ owner decision) | measured (absent) | [gaps.md](gaps.md) | | Agent automation (MCP, CLI, control channel) | beyond Illustrator | — | measured | [mcp.md](mcp.md) | @@ -692,12 +685,12 @@ since 2026-10-01. - **`.ai` clipping paths grouped in a compound path (#8128):** `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs` covers clipping paths grouped in a compound path (`*u u <path> W n … U *U`, also nested in other groups): they are the compound path's subpaths, and the compound clipping path, their union, clips its clipping group however many there are and wherever in the group it is written. Synthetic files written in the test; no fixtures added. Scores and hours unchanged. -**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. +**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/it/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). - Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). -- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. +- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/it/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. @@ -706,7 +699,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step; beside a moved corner anchor a line stays a line and an arc an arc, and at a moved smooth anchor the handles stay in line and the segments bend to meet), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `a_release_past_the_drag_distance_moves_the_anchor`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. - **Recolor with Preset asks for a library first:** Edit › Edit Colors › Recolor with Preset (1, 2 and 3 Color Job, Color Library) opens a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=251>, "Quickly reduce colors using a preset"). A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch, so editing the swatch recolors the art. Tests `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. Area score and hours unchanged. -- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` and Ctrl with a touchpad scroll or a mouse wheel over the canvas change the arc size by 15° (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`), a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, C, `[` and `]` changing the arc being dragged, the mouse wheel changing the arc size, and one step per net whole wheel line of a mouse wheel are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `tests::quickpenwheel`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. @@ -716,7 +709,7 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. @@ -727,7 +720,7 @@ since 2026-10-01. - **PDF Indic type (#5235, #6906):** `crates/pdf/src/tests/reshaped.rs` covers a vowel sign the file draws before its consonant (the line keeps the file's glyphs as outlines, with a note), text in reading order (stays type), a mark with no advance (stays on its line, not vertical type of its own), outlined glyphs stroked with different dashes and translucent outlined glyphs (each keeps its own path). Synthetic font only; one real Gujarati file checked by eye on page 1. Indic type in an uninstalled font keeps the file's glyphs as outlines; reordering signs so more lines stay editable is not done. Scores and hours stay at 75% / 10-20 h. -- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. +- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/it/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. @@ -757,7 +750,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on, the box and the dimension reach the outside of the path's strokes, which is the size W and H show when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows the box its strokes paint, which reaches 0.5 pt past its outermost points for a centered 1 pt stroke (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. @@ -834,7 +827,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. -- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. @@ -843,7 +836,7 @@ since 2026-10-01. - **Ctrl/Cmd-click and Shift-click on Layers panel target circles (#8639):** the target circles follow the same modifier rules as the row names, as the help page describes for selecting objects in the Layers panel: Shift for adjacent objects, Ctrl or Command for non-adjacent ones ([Move objects to different layers](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/move-objects-to-different-layers.html)). Ctrl/Cmd-click adds the item (a layer: its art) to the selection or takes it out, which Shift-click did before (#913); Shift-click selects the art of every row from the last circle clicked (else the targeted row) to this one, and Shift+Ctrl/Cmd-click adds it (`layer.target {range, add?}`). Hidden or locked art and art outside the isolated group in the range is left out, and nothing stays targeted. Regression tests: `clicking_a_target_circle_targets_the_layer` and `shift_clicking_a_target_circle_selects_a_range_of_rows` in `crates/ui-egui/src/panels/layers/tests.rs`. - **Shift-click in the Layers panel's selection column selects the art of a range of rows:** after a selection square is clicked, Shift-clicking another selects the art of every row listed from the last square clicked to this one, down or up and across sublayers and groups, and Shift+Ctrl/Cmd-click adds that art to the selection (`layer.selectAll {range, add?}`). Hidden and locked rows and art outside the isolated group are left out, and a range does not move where the next Shift-click starts. Ctrl/Cmd-click adds one row's art or takes it out, and so does Shift-click before any square was clicked. The panel menu's Select Art of Highlighted Rows (`layer.selectHighlighted`) selects the art of the highlighted rows by the same rules. These are VectorCraft's own rules. Regression tests: `shift_clicking_a_selection_square_selects_the_art_of_a_range_of_rows` and `shift_clicking_the_first_selection_square_adds_or_removes_one_row` in `crates/ui-egui/src/panels/layers/tests.rs`, `the_selection_column_selects_the_art_of_a_range_of_rows` and `select_highlighted_selects_the_art_of_the_highlighted_rows` in `crates/engine/src/tests/layers.rs`. - **Layers added to the selection from their target circles show as targeted (#8646):** with several items picked from their circles (nothing targeted), a layer or sublayer's circle shows its inner ring while all of its visible, unlocked art is selected, as an object's circle does while the object is selected. A layer is never selected itself, only its art, so its circle used to keep a single ring. Regression test: `a_layer_added_from_its_target_circle_shows_as_targeted` in `crates/ui-egui/src/panels/layers/tests.rs`. -- **A targeted item with an appearance of its own shows both marks (#8711):** its target circle keeps the inner ring of a targeted item, with the appearance dot drawn smaller inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) do. The dot used to cover the ring. Regression test: `a_targeted_circle_with_an_appearance_shows_both_ring_and_dot` in `crates/ui-egui/src/panels/layers/tests.rs`. +- **A targeted item with an appearance of its own shows both marks (#8711):** its target circle keeps the inner ring of a targeted item, with the hollow diamond drawn smaller inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) do. The dot used to cover the ring. Regression test: `a_targeted_circle_with_an_appearance_shows_both_ring_and_dot` in `crates/ui-egui/src/panels/layers/tests.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. @@ -1086,6 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. + - Export Settings in the Asset Export panel scroll on their own in a short panel. - Export for Screens artboard names can be double-clicked to rename them in grid or list view (#7275). Enter, a click outside the field or switching to Assets commits the name; Escape cancels the edit. The dialog stays open, checked artboards stay selected and the rename is undoable. The typed name goes to the artboard that was double-clicked even when the artboards change order while it is typed; the field closes when its artboard is deleted or another document becomes active. Evidence: `dialogs::tests_screens::double_clicking_an_artboard_name_in_export_for_screens_renames_it`, `dialogs::tests_screens::switching_export_tabs_commits_an_artboard_name`, `dialogs::tests_screens::an_artboard_name_follows_its_artboard_while_it_is_typed` and `dialogs::tests_screens::an_artboard_name_stays_with_its_document`. - Asset Export tile context menus (2026-11-20): Export / Remove operate on the selected assets, with plural labels; Rename edits the clicked tile inline; Select Artwork on Canvas selects its source nodes; collecting selected artwork as one or multiple assets is enabled only with canvas selection. Right-click selects an unselected tile and preserves an existing multi-selection. Export shares the raster/3D path; removal is one undo step without removing art. Headless regressions: `panels::tests_asset_export` (selection, export targets, removal/Undo/Redo, source artwork, rename and collection). This reduces G12; UI parity scores and estimates are unchanged. - Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`. @@ -1127,10 +1121,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. + - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. + - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. + - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. @@ -1198,7 +1196,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. + - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,514 of 1,514 runs pass. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. @@ -1362,7 +1360,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In that Liquify warning, the tool's name and each kind of object it left (graphs, type, symbols, images, meshes, envelopes, repeats, placed documents, blends) are shown in the interface language too, in the order the command lists them and joined as the language joins a list, in each catalog that translates all status and error messages (`liquify-tool`, `liquify-kind` and `liquify-list-*` rows); a kind that Liquify does not list leaves the tool and the list in English (`liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog`). - An effect a plug-in's output or an importer plug-in's objects carry that VectorCraft refuses (``[0] `id`: reason``) shows in the status bar with its reason in the interface language inside `plug-in output: …` and `can't open …`, in every catalog that translates all status and error messages; the index and the effect id stay as they are, and a JSON array in a message stays as it is (`nested_effect_refusals_translate_with_their_reason`, `bracketed_message_parts_translate_only_as_exact_messages`). - A filter run (`plugin.run`) or plug-in command whose output changes no object and none of the data the plug-in keeps with the document records no undo step and leaves a saved document unmodified, with its objects still selected; a run that may call commands records none when its calls leave the document as it was (engine `plugins::a_filter_run_that_changes_nothing_records_no_undo_step`, `plugins::a_filter_that_keeps_the_same_data_records_no_undo_step`, `plugins::a_plugin_command_that_changes_nothing_records_no_undo_step`). - - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). + - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). - The Swedish catalog has rows for the Apply SVG Filter and Check Spelling command names, the SVG Filter effect's name, which also names its undo step, and the 3D and Materials panel's note that graphics map onto the Plane, Extrude and Revolve object types, so these show in Swedish instead of English (`swedish_svg_filter_spelling_and_3d_labels_are_complete`). - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. @@ -1383,7 +1381,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Dynamic symbol instances on the canvas** ([Symbols, archived copy](https://web.archive.org/web/20240206075757/https://helpx.adobe.com/illustrator/using/symbols.html)): each instance of a dynamic symbol can have an appearance of its own while it shares the symbol's shape. The rest of this entry is VectorCraft's own rules. A Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of the symbol's art under the pointer and outlines it (`symbol.instance.selectPart`); the Swatches and Color panels, the Control bar, the Eyedropper and the other fill and stroke controls then change that object's fill or stroke (solid, none, gradient or pattern) for this instance only, each as one undo step, and `transparency.set` changes its opacity and blend the same way; the symbol's art and its other instances stay as they were. Alt or Shift picks the instance whole. An Eyedropper source that is not a path, compound path or type, a click on any other object of the art (a group, image, blend or nested instance) and the commands that change the selected objects (moving, Delete, Group, Hide, Lock, Arrange, Expand, the gradient annotator, isolate/knockout on Transparency, the Appearance panel's rows and others) are refused with a status message. Copy, Export Selection, Fit to Selection, Liquify, Isolate, Add to Library and Save Selection use the whole instance (`docs/mcp.md`), and another selection tool selects the instance whole again. Tests: `crates/engine/src/tests/dynamic_symbols.rs` (`gradients_and_patterns_on_a_picked_object_are_taken`, `opacity_and_blend_on_a_picked_object_go_through_transparency_set`), `direct::tests::a_click_on_a_dynamic_instance_picks_the_object_under_the_pointer`. - **Stained symbol instances in export** ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136), Stain symbol instances): an instance colored with the Symbol Stainer is exported in the colors the canvas draws it in. The mix is VectorCraft's own rule: after a dynamic symbol's own changes, the instance's visible fill mixes the solid fills and strokes of the symbol's art, type included, toward the fill's color by the fill's opacity; a hidden fill or one at 0% leaves the art's colors as they are. SVG, PDF (printing to PDF included), EPS, legacy `.ai`, DXF, EMF and WMF write the stained colors for an instance on its own, in a group, placed through 9-slice guides or reshaped by its geometry effects, and a color adjustment on the instance recolors the stained art. Tests: `bake::tests::a_stained_instance_is_baked_in_its_stained_colors` (vectorcraft-effects), `tests::a_stained_instance_keeps_its_stain` (vectorcraft-pdf), `symbols_layers::a_stained_instance_with_a_geometry_effect_keeps_its_stain` (vectorcraft-svg), and `a_stained_instance_is_written_in_its_stained_color` in vectorcraft-eps (EPS and legacy `.ai`), vectorcraft-cad and vectorcraft-metafile (EMF and WMF). - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it may pass the art's edges (see the next entry) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). + - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art, and their standard SVG data and `.ai` editing data for other apps keep no guides; when VectorCraft reopens an `.ai`, or an SVG saved with Preserve Editing Capabilities (`preserveEditing`), from the VectorCraft document embedded in it (the embedded document must be current and readable), the guides return. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`, `a_symbol_dragged_from_another_document_is_not_duplicated`. @@ -1468,6 +1466,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). + - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. @@ -1531,6 +1530,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it, leaving out a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). @@ -1594,10 +1594,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`. - The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). + The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). - The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. - With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. + The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/it/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. + With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. @@ -1830,7 +1830,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). - - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. The shared planar map keeps a segment cap (65,536 since #937, was 4,096) and its filled-area fallback; other Pathfinder operations are unchanged. + - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. Divide with open paths stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments (since #937, the cap was 4,096), have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. Other Pathfinder operations are unchanged. - Type that Transform effects only move and copy (no scale, rotation, reflection or Random) exports as type in each place, and PDF export writes every copy as selectable, searchable text, when its characters are in solid colors without underline or strikethrough, the type object has no fills or strokes of its own, no inline graphics and no perspective, its transform does not scale or shear stroked characters, and the copies do not overlap. When the effect is on the type itself, the type can also have transparency, an opacity mask and raster effects. When the effect is on the group or layer holding the type, the type has no transparency or effects of its own and is not in a clipping path, the group or layer has no fill, stroke or Pathfinder effect of its own, and no group between them has a fill, stroke, Pathfinder or geometry effect. Type still exports as outlines when the effect stops its copies early, or when the copies would number more than 10,000 or take more than 20,000,000 bytes of document data, and so does other type under a geometry effect. - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. @@ -2110,7 +2110,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Object › Live Paint › Expand keeps the faces and edges that draw on the canvas, with all their fill and stroke rows, so the expanded paths look as the painted group did ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, a face or edge draws when it is shown, its opacity is above 0, and any of its fill or stroke rows is shown, has paint and an opacity above 0 (a stroke also needs a weight above 0), whichever row is on top: a painted lower row under an unpainted top row is kept, and a part whose only painted row is hidden is removed. Merge copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. Evidence: `tests::build::{live_paint_expand_keeps_the_faces_and_edges_that_draw, live_paint_merge_carries_the_faces_that_draw, live_paint_merge_leaves_pen_pressure_behind, live_paint_merge_keeps_the_fit_of_carried_gradients, live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts}`. `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, with its paint, opacity, visibility, weight for a stroke, and whether it draws by the rule above, beside the top fill, stroke and weight it already reported. Evidence: `tests::build::live_paint_info_lists_every_appearance_row`. - Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color, and a preview that fails puts the groups back and stops drawing the dialog's preview of the gaps. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. @@ -2207,6 +2207,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (<https://fogra.org/en/downloads/work-tools/characterisation-data>), which ships unmodified: the measured paper, solids and overprints, a tone curve fitted to each ink's ramp, and a smoothed Lab correction lattice fitted to all 1,617 patches. The models reproduce the patches within a mean ΔE2000 of 0.04 (largest 0.37), and patches left out of the fit within 0.15 to 0.17 (largest 1.67). A PDF/X output intent made with one embeds the profile; with the condition identifier left blank it names `FOGRA51` or `FOGRA52`, in the `http://www.color.org` registry unless the settings give a registry, and an identifier the settings give is written as given. The 300% ink limit and black generation are VectorCraft's own values. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **My Themes row menu:** Opening a saved theme's row menu selects it and offers Edit Theme, Add to Swatches and Delete Theme. Add to Swatches requires an active document. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. @@ -2245,6 +2246,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Pattern Brush Options' Scale has a menu of Fixed, Pressure, Tilt, Bearing, Rotation and Stylus Wheel with a second scale beside it, in the library brush's dialog and in Options of Selected Object, from the pen tablet options the Pattern brush options section of the help page (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189>, archived copy) lists for Scale (`brush.options` and `brush.objectOptions` `scale_mode` and `scale_max`). The tiles go from Scale where the pen reads 0 to the second scale where it reads 1, over the same ranges as Art Brush Options' Width, and half way on a stroke without that input. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile is as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit stretches the tiles and gaps of each run to fill it, Add Space to Fit shares out what is left between the tiles, and Approximate Path centers them on the run. The help page does not say how the pen maps to the scale or how the tiles are measured along the stroke, so those rules are VectorCraft's own. A brush with a fixed scale draws as before. `.ai` files do not read or write the pattern scale's mode, and the Width tool does not turn the pen's data into width points. Evidence: `tests::pattern_brush_scale_follows_the_pressure`, `tests::pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel`, `tests::pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles` (vectorcraft-brush), `tests::brushsym::options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes`, `tests::brushsym::pattern_brush_scale_mode_goes_through_the_brush_commands` (vectorcraft-engine), `dialogs::brush_options::tests::pattern_options_scale_follows_the_pen`, `dialogs::brush_options::tests::options_of_selected_object_set_one_paths_pattern_scale_mode` (vectorcraft-ui-egui). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (<https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure>), for each move of a pen including the positions a fast stroke's events coalesce. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (<https://developer-docs.wacom.com/docs/icbt/windows/wintab/wintab-reference/>, <https://developer-docs.wacom.com/docs/icbt/windows/wintab/wintab-basics/>). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS and in the web build; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. These are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). + - **Brush edits that change nothing add no undo step:** Brush Options that leave a brush as it is, and Apply Brush of the current brush to paths whose top strokes already have it, paint, a width above 0 and no settings of their own, leave the document and its undo history as they are. Apply Brush clears the settings of the top stroke (Options of Selected Object), and clearing them is one undo step. Evidence: `tests::brushsym::brush_apply_that_changes_nothing_records_no_undo_step` and `tests::brushsym::brush_apply_clears_object_options_as_one_undo_step` (vectorcraft-engine). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). @@ -2388,6 +2390,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG Options › Units writes export `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, with the `viewBox` in points (#4462). Physical dimensions require Responsive off and a physical unit; Responsive omits both dimensions. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -2402,6 +2405,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. SVG export (Save As, Export As, Export for Screens, Asset Export and the clipboard share the writer) writes simple shapes as SVG basic shapes, as the reference app does (an ellipse is an `ellipse` tag until an anchor is added, [forum](https://community.adobe.com/t5/illustrator-discussions/trouble-exporting-shape-with-points-to-svg/td-p/10720325); rectangles come out as `<rect>` and `<polygon>`, [forum](https://community.adobe.com/t5/illustrator-discussions/force-svg-export-using-all-lt-rect-gt/td-p/11282378)): an axis-aligned rectangle as `<rect>`, a circle or ellipse drawn with four standard arcs as `<circle>`/`<ellipse>`, a straight line as `<line>`, and other straight-segment paths as `<polygon>`/`<polyline>`, at the written precision (#4652). A rectangle or ellipse with a dashed stroke, whose dashes would start elsewhere, a turned ellipse, curves and compound paths stay `<path>`. `crates/svg/tests/it/basic_shapes.rs` checks each element, that the picture renders as the canvas does and that the geometry reimports. At a precision of 9 decimals or fewer, SVG export writes each number from an integer when the integer rounds it as the decimal formatter does; the formatter still writes values halfway between two written numbers and values too large for the integer. Exporting one path of 200,000 anchors takes a median of 43.4 ms instead of 167.0 ms on Windows 11, and 20,000 rectangles 81.4 ms instead of 141.4 ms, with the same SVG (`crates/svg/src/lib.rs`). + Physical SVG sizes require both disabling SVG Options › Responsive and selecting Points, Millimeters, Centimeters or Inches under Units; Responsive omits `width` and `height`, so selecting a unit alone does not set physical size. Physical dimensions retain at least six decimal places and six significant digits independently of coordinate precision. Legacy Pixels output remains bare numbers, one per document point, rather than a physical-size guarantee: CSS pixels are 96 per inch. Regression coverage: `physical_units_preserve_rendered_extent_at_low_coordinate_precision` checks a consumer's viewport and drawn extent under default aspect-ratio scaling, including narrow and tiny artboards; `tiny_physical_sizes_keep_their_scale` covers smaller converted lengths. SVG import reads each `<circle>` and `<ellipse>` as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right, with handles of the standard length, so an ellipse exported as `<ellipse>` comes back with the anchors it was written from and draws the same (`circles_and_ellipses_import_as_the_ellipse_drawn` in `crates/svg/tests/it/basic_shapes.rs`, `filled_ellipse_on_the_artboard_edge_survives_visually` in `prop_svg.rs`). SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). @@ -2793,7 +2797,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Rough Pastels' Load Texture:** Effect › Artistic › Rough Pastels… has the same Load Texture… button, and its Texture and Light Direction controls are menus. The loaded image's gray levels are the paper surface (Loaded Texture in the Texture menu, `textureImage` stored with the effect), and Scaling, Relief, Light Direction and Invert act on it as on Brick, Burlap, Canvas and Sandstone (`pixel::tests::rough_pastels_draws_a_loaded_texture_as_its_surface`, `rough_pastels_loads_a_texture_saves_it_and_draws_it`). - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Crystallize Cell Size 3..300 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. -- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 3), and a file saved for an older app version holds them in points again. +- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 3), and a file saved for an older app version holds them in points again. Saved RGB Color Halftone artwork can render differently when reopened: light tones now produce dark dots on a light background, and the first three angle controls now set the cyan, magenta and yellow ink screens. CMYK mode also screens black ink. A full-strength dot reaches its cell corners and can overlap the edge of an adjacent cell. The overlap is bounded by the circle and its antialiased edge. - **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace, Color Halftone), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434). @@ -2896,7 +2900,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. Colored Revolve's faces lie over an underlay of themselves the same way, run by run in a group and with mapped graphics kept after their faces; `colored_revolve_faces_leave_no_alpha_holes_at_one_to_one` checks that no pixel inside the art lets the background through at 1:1 where 3x averaged down is opaque, live, read back from SVG and PDF, and expanded. -Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::turned_colored_inflate_facets_and_seams_cover_their_edges_once` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. +Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. ## Eyedropper character dimensions (2026-11-11) @@ -3128,6 +3132,11 @@ tints, curves, multiplied inks, skip spot), `duotone_*` and `cmd::addons::color: params and RGB documents refused), and `the_duotone_dialog_has_a_row_per_tone_and_the_curve_of_one` and `print_ink_fixes_opens_its_options_and_runs_on_ok` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Color Effects add-on. + +## Color Effects add-on: Randomize Fill Colors (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Objects without a fill, clipping paths, hidden and locked objects, objects inside hidden or locked groups and layers or on a locked artboard, generated graph design art, type, images, symbol instances, blends and envelopes keep their fills. New art made on a locked artboard takes a color while it is still selected. The command records one undo step when a fill changes and rejects bad params without a change. Tests: `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths, live compound shapes and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. + ## Arrange Tools add-on (2026-10-31) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools: Arrange in @@ -3166,6 +3175,14 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + +## Arrange Tools add-on: Group by Row (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Group by Row… puts the top-level selected objects (at most 20000) into one group for each row: an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row from top to bottom. Group By Columns does the same from left to right. Extents that only touch stay apart, an object that overlaps two rows joins them, and only objects in the same layer or group and on the same artboard share a row; an object alone in its row stays as it is. Each new group takes its frontmost member's place in the stacking order, and the groups and the objects left alone stay selected. One undo step; no step when no row holds two objects. Tests: `group_rows_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (rows and loners, columns, an object spanning two rows, layers and artboards kept apart, strokes and clipping groups, locked objects left out, bad params, 20000 objects), `real_group_by_row_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. @@ -3414,6 +3431,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | +| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | @@ -3461,6 +3480,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | Type: kerning at the Type tool's caret at the start of a line (the text's, a paragraph's, or after a forced line break) sets the space before the character after it (`kerningBefore`), which moves it and the rest of its line; it did nothing at the text's start and kerned the invisible line break at a paragraph's (#5111). Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-11 | minor | SVG physical dimensions retain scale independently of coordinate precision, including tiny sizes (#5450 review); consumer-rendered extent regression added. Clarify that physical output requires Responsive off and a physical unit; legacy bare numeric output is unchanged and CSS pixels are 96/in. Scores and estimates unchanged. | | 2026-11-11 | minor | Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does (Smart Guides, Snap to Point and the ruler guides, pixels, the grid); evidence updated; scores unchanged. | | 2026-11-11 | minor | Interim macOS canvas cursor delivery (#2292): the tool's cursor stays after the pointer moves (#6362); tool cursors evidence updated; scores and hours unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | @@ -3523,6 +3543,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Area type vertical alignment buttons in the Properties panel's Paragraph section and the Control panel, off for columns, rows and threaded frames (#3759); evidence added; scores unchanged. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for exported `width` and `height`. For physical size in laser and plotter software, disable Responsive and select a physical unit; Responsive omits both dimensions, so selecting a unit alone does not help (#4462; Pixels still bare numbers as before). Scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-03 | minor | The canvas context menu offers Outline Stroke for a stroked selection (#5267); scores and estimates unchanged. | | 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | @@ -3864,4 +3885,4 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. diff --git a/docs/type-parity.md b/docs/type-parity.md index 60b4a7117d..9d3d069cc8 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -57,7 +57,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | -| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | +| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | | Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu and the context menu, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d131053a67..001ff1141c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,12 +1,14 @@ # UI and interaction parity > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > > Outline Stroke is available in the canvas context menu when the selection has an outlinable stroke (#5267). A linked dimension selected with its source keeps its lines; those protected lines do not make a fill-only source eligible, including inside a group. Coincident-point paths with a plain butt-capped stroke do not make the selection eligible either; round and square caps still paint and can be outlined. Scores and estimates unchanged. > +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. Save As and Save a Copy offer Document units and preserve an existing SVG's physical units when legacy saved options omit a unit; Export keeps its Pixels default. +> > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -25,7 +27,11 @@ ## Feature submission evidence -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. + +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -168,18 +174,18 @@ forbids launching or measuring Illustrator, so there has been **no side-by-side | Area | % | Remaining (h) | Kind | |---|---:|---:|---| -| Pen, Curvature and anchor tools | 85% | 6–10 | estimated | -| Direct Selection, handles and anchors | 85% | 5–8 | estimated | -| Smart guides and snapping | 70% | 8–12 | estimated | -| Transform handles, bounding box, Free Transform | 80% | 5–8 | estimated | +| Pen, Curvature and anchor tools | 90% | 6–10 | estimated | +| Direct Selection, handles and anchors | 90% | 5–8 | estimated | +| Smart guides and snapping | 85% | 8–12 | estimated | +| Transform handles, bounding box, Free Transform | 90% | 5–8 | estimated | | Nudging, numeric entry, precision, units | 85% | 3–5 | estimated | -| Modifier keys and temporary tools | 80% | 5–8 | estimated | -| Keyboard shortcuts (default set) | 70% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | -| Cursors | 75% | 3–5 | estimated | -| Panels, Control bar, Properties, context menus | 70% | 15–25 | estimated | +| Modifier keys and temporary tools | 85% | 5–8 | estimated | +| Keyboard shortcuts (default set) | 75% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | +| Cursors | 80% | 3–5 | estimated | +| Panels, Control bar, Properties, context menus | 80% | 15–25 | estimated | | Look and feel (layout, theme, metrics) | 80% | 5–10 | measured once against public screenshots on 2026-10-02; panels added since not re-measured | -| Accessibility (screen reader, keyboard-only canvas) | 20% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | -| **UI/UX overall** | **~55%** | **~70–110** (overlaps the feature areas) | estimated | +| Accessibility (screen reader, keyboard-only canvas) | 25% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | +| **UI/UX overall** | **~60%** | **~70–110** (overlaps the feature areas) | estimated | The overall figure is lower than the rows because what users notice first (small differences across many tools, never checked side by side) isn't captured row by row. @@ -204,19 +210,19 @@ tools, never checked side by side) isn't captured row by row. | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | -| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | -| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | +| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. | +| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/it/scissors_snap.rs`. | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | +| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | | Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes and fill-only open paths lose the rectangle's area, other open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`). Not yet: Ctrl+scroll for the arc size | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` and Ctrl+scroll for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; Ctrl+scroll on a touchpad, and VectorCraft's own Ctrl+mouse wheel, over the canvas for the arc size in `crates/ui-egui/src/canvas/quick_pen_wheel.rs` (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`); with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`) | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | @@ -250,7 +256,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/it/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Backquote/~ arrow nudges move selected pattern fills and strokes | done | #7717: Selection, partial-anchor Direct Selection and other idle tools; Keyboard Increment/Shift; geometry, guides and anchor selection stay fixed. Tests: `crates/ui-egui/tests/pattern_only_nudge.rs` | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | @@ -269,7 +275,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | @@ -350,7 +356,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| | Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. This rule and its 0.5 s are VectorCraft's choices. Other font-picking menus and modifier-wheel input keep their existing behavior. | -| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | +| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Ctrl/Cmd ÷10 (Shift+Ctrl/Cmd: one increment), as the Transform panel fields step; Alt copies | done | Ctrl/Cmd ÷10 is VectorCraft's own addition (#5258) | | Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | | Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a hovered field without a click; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input or the pointer is pressed on a field, so a panel scrolled under a still pointer keeps scrolling past the field. This rule and its 0.5 s are VectorCraft's choices. | | Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | @@ -405,7 +411,7 @@ tools, never checked side by side) isn't captured row by row. | Artboard Options › Display: Show Center Mark and Show Cross Hairs ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html)) | done | Per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`, one undo step); the canvas draws a cross 12 points across on screen at the center and lines from the middle of each side through it, 1 point wide on screen at any zoom and turned with the view; exports and print leave them out; tests `an_artboard_shows_its_center_mark_and_cross_hairs`, `artboard_options_show_center_mark_and_cross_hairs` | | View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | | Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | -| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/ellipse_drag_anchors.rs` | +| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/it/ellipse_drag_anchors.rs` | | Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | | Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | | Tool double-click opens its options | done | | @@ -458,7 +464,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; craft-ui's `TypeRole::TabTitle` and `craft_fonts_build::Embed::tab_face`; `craft_fonts::tests::document_fonts_leave_out_the_tab_title_face`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; craft-ui's `TypeRole::TabTitle` and `craft_fonts_build::Embed::tab_face`; `craft_fonts::tests::document_fonts_leave_out_the_tab_title_face`; the CI, nightly, release and FreeBSD workflows pin craft-fonts `16bbfc3`, which has the face (storytold/craft-fonts#72), so official desktop builds made from them draw tab titles in it; web builds draw them in the semibold face; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | @@ -484,6 +490,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | +| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | @@ -521,6 +528,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | +| Swatch, Brush, Symbol and Graphic Style Library item menus | done | In list and thumbnail views, the item menu offers the same Add to action as the footer. It adds the current selection when the target is selected or the target alone otherwise. The action requires an open drawing. | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its fill or stroke (solid, gradient or pattern) and the Transparency panel setting its opacity and blend, is on canvas (#6308); `.ai` editing data keeps dynamic symbols and their instance changes when VectorCraft writes and reads it (#8747); on-canvas editing beyond fill, stroke, opacity and blend, and reading other apps' dynamic symbol records, remain | @@ -530,8 +538,9 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | -| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | +| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. The menu offers Create Outlines when the selection includes text directly or inside a selected group, with the same shortcut and undoable command as Type › Create Outlines (#9022). The Menu key and Shift+F10 open the menu for the current selection. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | +| Layers own-appearance marker (#8710) | implemented | Hollow diamond and tooltip distinguish own appearance/transparency from the targeting double ring and selected-art square; targeting, drag and Alt-copy behavior retained. Depends on Hassan1305's #8757 ring-visibility fix and retains its four-state coverage. `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation pending. | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | @@ -569,6 +578,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview; marks go above the object or its outermost clip group or clipping sublayer and become selected; one undo step | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group by Row… groups the selected objects whose visual bounds overlap from top to bottom into one group for each row, or with Group By Columns from left to right (within one layer or group and one artboard), each group at its frontmost member's stacking place; Preview; one undo step | done | `addon.arrange.groupRows`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | @@ -584,7 +595,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Common Tangents… with External and Curved (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/tangents.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | @@ -597,6 +608,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | | Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | +| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Randomize Fill Colors… picks Colors (Any Color, Tints of a Swatch or Grays), a Swatch among the document's global and spot swatches, Minimum and Maximum (%) and a Seed, with Preview, and gives each selected filled path and compound path, inside groups too, its own fill color at random, one undo step | done | `addon.color.randomFill`, `crates/engine/src/cmd/addons/color/random_fill.rs`, `crates/ui-egui/src/addons/color/random_fill.rs` and their tests; a VectorCraft addition, so it is not scored | | Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | | Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | | Style panels: a double-click on a user character style's row opens its Character Style Options, and on a paragraph style's row opens the same Paragraph Style Options as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings; the Character Style Options dialog keeps a fixed width, its sections scrolling when the window is shorter so OK and Cancel stay on screen | done | `ui.charStyleOptions`, `ui.paraStyleOptions` (`paraStyle.edit`); `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | @@ -672,8 +684,10 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-20 | minor | Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | +| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | | 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-20 | minor | Properties panel per context (G12): Quick Actions for text selection (Create Outlines, Retype, Find and Replace…); Retype reveals panel without toggling off if already open; headless tests in panels::properties::tests. Scores and estimates unchanged. | @@ -718,6 +732,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | +| 2026-11-09 | minor | Arrow keys: Ctrl/Cmd+arrow nudges art, direct-selected anchors, ruler guides and a selection in perspective by a tenth of the Keyboard Increment, and Shift+Ctrl/Cmd+arrow by one increment; `object.nudge` and `perspective.nudge` take `fine`; Snap to Grid no longer pulls a nudge in perspective back onto the gridlines, which left grid-aligned art unmoved (#5258); scores and estimates unchanged | | 2026-11-09 | minor | Numeric fields step on wheel hover without taking focus; keyboard focus and existing rounding rules remain (#5949). Scores and estimates unchanged. | | 2026-11-08 | minor | Floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part); tab groups remain intact. Scores and estimates unchanged. | | 2026-11-07 | minor | Pen and Curvature tool with Cmd/Ctrl held: Edit › Copy and Cut take the anchors and segments the lent Direct Selection picked, as with Direct Selection chosen, not the whole path; with the Pen's own last anchor selected Copy still takes the whole path (#6123); scores and estimates unchanged | @@ -738,6 +753,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-03 | minor | The canvas context menu offers Outline Stroke when the selection has a stroke to outline (#5267); scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | @@ -945,6 +961,6 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-10-22 | minor | Tab-drag follow-up: reconcile upstream progress updates and document drag lifecycle, insertion behavior and regression contracts; behavior, scores and estimates unchanged. | | 2026-10-22 | minor | Artwork dragged with Selection switches visible document tabs after a 400 ms hover, then copies editable artwork on canvas release; source and clipboard stay intact; scores and hours unchanged | -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. > **Text styles status (2026-11-19):** Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides) are implemented and covered by headless tests; parity scores and estimates are unchanged. diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index a284579d16..5684762f4e 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -36,6 +36,11 @@ def earlier(conclusion): return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}] +def split_job(shard, status, completed_at=None): + return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status, + "conclusion": "success" if status == "completed" else None, "completed_at": completed_at} + + class SaveStep(unittest.TestCase): def test_the_leg_is_saving_once_its_save_step_starts(self): self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)]))) @@ -99,6 +104,34 @@ class Deadline(unittest.TestCase): self.assertFalse(clear.started_late(warm_job("queued"), self.began)) self.assertFalse(clear.started_late(None, self.began)) + def test_split_progress_suspends_the_start_deadline(self): + for status in ("queued", "in_progress"): + with self.subTest(status=status): + jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)] + ready = clear.start_wait_began(jobs, self.began) + self.assertIsNone(ready) + now = self.began + timedelta(seconds=clear.START_SECONDS + 60) + self.assertFalse(clear.start_overdue(None, now, ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready)) + + def test_the_last_split_completion_starts_the_wait(self): + jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"), + split_job(2, "completed", "2026-11-28T07:00:00Z")] + ready = clear.start_wait_began(jobs, self.began) + self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z")) + self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready)) + self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready)) + late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat()) + self.assertTrue(clear.started_late(late, ready)) + + def test_without_split_legs_the_script_start_starts_the_wait(self): + self.assertEqual(clear.start_wait_began([], self.began), self.began) + self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began) + + def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self): + self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began)) + class Workflow(unittest.TestCase): ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() @@ -116,10 +149,17 @@ class Workflow(unittest.TestCase): self.fail(f"no timeout-minutes under {job}") def test_the_job_outlasts_the_start_wait_and_the_save_wait(self): - # Five minutes are left for the steps before the script and for the deletion. + # Without split legs, five minutes remain for setup and deletion. spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS self.assertGreaterEqual(spare, 5 * 60) + def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self): + # Runner waits and the full start allowance may exceed the 360-minute job limit. + timeout = self.timeout_minutes("cold-cache-clear") + spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS + self.assertGreaterEqual(spare, 5 * 60) + self.assertEqual(timeout, 360) + def test_the_save_wait_outlasts_the_gate(self): self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60) @@ -129,18 +169,26 @@ class Jobs(unittest.TestCase): jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] self.assertEqual(clear.warm_job(jobs), jobs[2]) - def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self): - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")})) + def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self): + grace = clear.RERUN_GRACE_SECONDS + failed_shard = [{"name": "gate / test 3/6 (ubuntu-24.04)", "status": "in_progress"}] + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME + failed_shard, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")}, grace)) + + def test_an_attempt_is_watched_for_the_grace_period_first(self): + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success")}, clear.RERUN_GRACE_SECONDS - 1)) def test_a_leg_that_did_not_succeed_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")})) - self.assertFalse(clear.not_in_attempt(ME, {})) - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")})) + grace = clear.RERUN_GRACE_SECONDS + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")}, grace)) def test_a_rerun_of_all_jobs_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")})) + select = [{"name": "gate / select legs", "status": "queued"}] + self.assertFalse(clear.not_in_attempt(ME + select, {1: earlier("success")}, clear.GIVE_UP_SECONDS)) def test_a_failed_select_or_build_stops_the_wait(self): done = lambda n, c: {"name": n, "status": "completed", "conclusion": c} @@ -148,6 +196,9 @@ class Jobs(unittest.TestCase): self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")])) self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")])) self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")])) + # With warm-split, the saving `cache warm (<os>)` leg also needs every `cache warm <k>/<N>` leg. + self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")])) + self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")])) class Caches(unittest.TestCase): @@ -184,6 +235,60 @@ class Clock(datetime): return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc) +class BeforeSaving(unittest.TestCase): + def run_main(self, polls): + began = Clock.now() + current = began + remaining = iter(polls) + + class PollClock(datetime): + @classmethod + def now(cls, tz=None): + return current + + def gh(url): + nonlocal current + if "/jobs?" in url: + minutes, jobs = next(remaining) + current = began + timedelta(minutes=minutes) + return {"jobs": ME + jobs} + if "/caches?" in url: + return {"actions_caches": []} + return {"run_started_at": began.isoformat()} + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \ + mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()): + status = clear.main() + delete.assert_not_called() + return status + + def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + saved = warm_job("completed", "success", [("Post Setup", "completed", "success")], + started_at="2026-11-28T07:50:00Z") + self.assertFalse(self.run_main([ + (181, [split_job(1, "queued")]), + (201, [split_job(1, "in_progress"), warm_job("queued")]), + (220, [done, warm_job("queued")]), + (230, [done, saved]), + ])) + + def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + self.assertEqual(self.run_main([ + (220, [done, warm_job("queued")]), + (401, [done, warm_job("queued")]), + ]), 1) + + def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)], + started_at="2026-11-28T10:40:01Z") + self.assertEqual(self.run_main([(401, [done, late])]), 1) + + class AfterDeletion(unittest.TestCase): SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)] @@ -222,9 +327,17 @@ class AfterDeletion(unittest.TestCase): canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) self.assertEqual(self.run_main(canceled), 1) + def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self): + skipped = warm_job("completed", conclusion="skipped") + failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"} + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(clear.main(), 1) + def test_a_leg_that_starts_late_and_saves_deletes_nothing(self): - # Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script. - late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z") + # Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script. + late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z") deleted = [] def run(args, **kwargs): diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3b913d68f7..6a9f3cdc88 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -16,11 +16,14 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re- runs it again beside the re-run leg. A save step that is canceled or fails after the old entries were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure in a later post step does not count once the save step has succeeded. This also exits 1 when the -leg has not started START_SECONDS after this script started, and when the leg has not reached its -save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only -when the most recent earlier attempt that lists it reports success and the current attempt lists -no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling -because reusable-workflow dependencies may still be scheduling it. +leg has not started START_SECONDS after the last split warm leg completed (or after this script +started when there are no split legs). The start deadline does not expire while a split leg is +queued or running. This exits 1 when the leg has not reached its save, or its save has not finished, +GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only +when the most recent earlier attempt that lists it reports success and the current attempt still +lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all +jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not. +Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. """ from datetime import datetime, timezone @@ -33,10 +36,17 @@ import time REF = 'refs/heads/main' WARM_JOB = re.compile(r'^gate / cache warm \(') +SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of -# them fails or is canceled, the legs are skipped and no warm leg is listed. -NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') -PRUNE_JOB = 'cache prune' +# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the +# saving leg also needs every `cache warm <k>/<N>` leg. +NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()') +# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it +# failed, and then no warm leg succeeded before. +SELECT_JOB = 'gate / select legs' +# How long an attempt that does not list SELECT_JOB is watched before the warm leg counts as +# finished in an earlier attempt. +RERUN_GRACE_SECONDS = 5 * 60 ROLLING = '-gate-crates-' # The gate-setup action's post step, which saves the dependency cache (craft-common-actions # actions/gate-setup, under the gate's `Setup` step). @@ -46,12 +56,11 @@ PAGE_SIZE = 100 # Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold # leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 -# How long the leg may take to start, timed from this script's start: the leg waits for -# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on -# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than -# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job -# times out. -START_SECONDS = 120 * 60 +# How long the saving leg may take to start after the last split warm leg completed, or after +# this script started when there are no split legs. Queued or running split legs suspend this +# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before +# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long. +START_SECONDS = 180 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) @@ -97,16 +106,25 @@ def started_at(job): return parse_time(started) if started else None +def start_wait_began(jobs, began): + """The last split warm completion, the script's start without splits, or None while waiting.""" + splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])] + if not splits: + return began + if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits): + return None + return max(parse_time(j['completed_at']) for j in splits) + + def start_overdue(job, now, began): - """True once START_SECONDS have passed since `began` (this script's start) and the warm leg - has not started.""" - return started_at(job) is None and (now - began).total_seconds() > START_SECONDS + """True once START_SECONDS have passed since the start wait began and the leg has not started.""" + return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS def started_late(job, began): - """True when the warm leg started more than START_SECONDS after `began` (this script's start).""" + """True when the warm leg started more than START_SECONDS after the start wait began.""" started = started_at(job) - return started is not None and (started - began).total_seconds() > START_SECONDS + return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS def gave_up(job, now): @@ -135,9 +153,10 @@ def legs_stopped(jobs): return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs) -def not_in_attempt(jobs, earlier_jobs): - """True when no prune job is listed and the most recent earlier warm leg succeeded.""" - if any(j['name'] == PRUNE_JOB for j in jobs): +def not_in_attempt(jobs, earlier_jobs, waited): + """True when SELECT_JOB is not listed `waited` seconds after this script started, at least + RERUN_GRACE_SECONDS, and the most recent earlier warm leg succeeded.""" + if waited < RERUN_GRACE_SECONDS or any(j['name'] == SELECT_JOB for j in jobs): return False for attempt in sorted(earlier_jobs, reverse=True): job = warm_job(earlier_jobs[attempt]) @@ -173,7 +192,8 @@ def main(): while True: jobs = gh(jobs_url) or {} job = warm_job(jobs.get('jobs', [])) - if started_late(job, began): + ready = start_wait_began(jobs.get('jobs', []), began) + if started_late(job, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if job and saving(job): @@ -185,20 +205,21 @@ def main(): earlier_jobs[earlier] = previous.get('jobs', []) if warm_job(earlier_jobs[earlier]) is not None: break - if not_in_attempt(jobs.get('jobs', []), earlier_jobs): + if not_in_attempt(jobs.get('jobs', []), earlier_jobs, (datetime.now(timezone.utc) - began).total_seconds()): print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') return if legs_stopped(jobs.get('jobs', [])): print('::error::the gate stopped before its cache warm leg started; nothing deleted') return 1 if job and job['status'] == 'completed': - if job.get('conclusion') in STOPPED: + # A saving leg skipped because a leg it needs failed (a `cache warm <k>/<N>` leg). + if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])): print(f'::error::{NO_SAVE}') return 1 print('the cache warm leg finished without a save step; nothing deleted') return now = datetime.now(timezone.utc) - if start_overdue(job, now, began): + if start_overdue(job, now, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if gave_up(job, now): diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6d935ae8fd..7a5c83e8b5 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,3 +10,7 @@ workspace = true [dependencies] serde_json = { workspace = true } + +# The files of other crates that this crate compiles, for CI's test selection. +[package.metadata.craft] +reads = ["crates/text/build/web_fonts.rs"] diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index f2fb1f1ce0..869074b03f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -80,6 +80,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["pathops", "trace"], &["text", "effects"], &["render", "eps"], + // SVG import sizes its element limit from the installed memory the renderer reads (#10165). + &["render", "svg"], &["metafile", "eps"], // Non-native art in Illustrator editing data is a PDF, drawn by the PDF importer. &["pdf", "eps"], diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..ce60771034 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -18,6 +18,7 @@ mod sha256; mod shards; mod stats; mod test262; +mod test_lint; mod ui_commands; mod version; mod web_fonts; @@ -32,6 +33,12 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + test-lint [--base <rev>] [--all] + weak tests in the lines changed since the base: fail on self-compares, reasonless + #[ignore], sleeps, reads of Rust source and tests no CI target runs; list only + is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env + gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit + by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,10 +46,11 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with + GATE_SHARD of GATE_SHARDS set, only what that shard builds; with CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace @@ -74,6 +82,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("test-lint") => test_lint::run(&root(), &rest), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -118,13 +127,13 @@ pub fn root() -> PathBuf { pub fn repo_files(root: &Path) -> Result<Vec<String>, String> { let out = Command::new("git") .current_dir(root) - .args(["ls-files", "--cached", "--others", "--exclude-standard"]) + .args(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]) .output() .map_err(|e| format!("git ls-files: {e}"))?; if !out.status.success() { return Err(format!("git ls-files failed: {}", String::from_utf8_lossy(&out.stderr).trim())); } - Ok(String::from_utf8_lossy(&out.stdout).lines().filter(|l| root.join(l).exists()).map(str::to_owned).collect()) + Ok(String::from_utf8_lossy(&out.stdout).split('\0').filter(|l| !l.is_empty() && root.join(l).exists()).map(str::to_owned).collect()) } /// A `cargo` command (the one running xtask, else `cargo` on the PATH) run in the workspace root. @@ -267,12 +276,14 @@ fn cmd_test() -> Result<(), String> { test_packages(&["--workspace".to_owned()], "--workspace", None) } +/// The test targets that [`test_packages`] runs and `ci warm` builds. +const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; + /// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; /// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. /// A part runs its counted share, then its pinned tests, each with nextest's default thread count. /// Every run finishes before the first error is returned. fn test_packages(select: &[String], shown: &str, part: Option<shards::Part>) -> Result<(), String> { - const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; if let Some(part) = part { if !has_nextest() { return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); @@ -393,34 +404,51 @@ fn cmd_ci_shard() -> Result<(), String> { run_steps(&steps) } -/// `cargo xtask ci warm`: for each test shard, builds its crates' library and binary tests without -/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the -/// dependencies of every shard with the features that shard builds them with (cargo resolves -/// features over the packages each command selects). The integration tests are left out: they -/// build no dependency that the library tests do not, since both take the crate's dev-dependencies. +/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration +/// tests without running them, then builds what the checks shard builds, so one dependency-cache +/// entry holds the dependencies of every shard with the features that shard builds them with (cargo +/// resolves features over the packages each command selects). The test builds select the same +/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the +/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that +/// only an integration test uses. +/// +/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that +/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build +/// nothing in either case, since part 1 builds the same tests. /// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. fn cmd_ci_warm() -> Result<(), String> { + let var = |key: &str| match std::env::var(key) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")), + }; + let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?); + let only = shards::warm_only(shard.as_deref(), count.as_deref())?; cache_units::record_xtask()?; let checked = shards::run()?; + let (tests, checks) = shards::warm_plan(&checked, only); let mut steps: Vec<Step> = Vec::new(); - for shard in checked { - // A split's later parts build the same tests as its first. - if let shards::Shard::Tests(crates, part) = shard { - if part.is_some_and(|p| !p.is_first()) { - continue; - } + for i in tests { + if let shards::Shard::Tests(crates, _) = checked[i].clone() { steps.push(( "build tests", Box::new(move || { - let mut c = cargo(); - c.arg("test").args(shards::select(&crates)).args(["--lib", "--bins", "--no-run"]); - cache_units::run(c, &format!("cargo test --lib --bins --no-run ({})", shards::names(&crates))) + let (c, what) = warm_tests(&crates); + cache_units::run(c, &what) }), )); } } + if checks { + push_warm_checks(&mut steps); + } + run_steps(&steps) +} + +/// The builds of the checks shard that [`cmd_ci_warm`] runs. +fn push_warm_checks(steps: &mut Vec<Step>) { steps.push(( "clippy", Box::new(|| { @@ -444,7 +472,13 @@ fn cmd_ci_warm() -> Result<(), String> { }), )); steps.push(("wasm", Box::new(cmd_wasm))); - run_steps(&steps) +} + +/// The command `ci warm` builds one test shard's tests with, and its description. +fn warm_tests(crates: &[shards::Member]) -> (Command, String) { + let mut c = cargo(); + c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates))) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed @@ -515,6 +549,7 @@ fn ci_steps() -> Vec<Step> { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), + ("test-lint", Box::new(|| test_lint::run(&root(), &[]))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), @@ -588,3 +623,20 @@ fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> { c.arg("test").args(select).args(["--lib", "--bins", "--tests", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture")) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn warm_builds_the_test_targets_the_shards_run() { + let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }]; + let (c, what) = warm_tests(&crates); + let args: Vec<String> = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); + for target in TARGETS { + assert!(args.iter().any(|a| a == target), "ci warm does not build {target}"); + } + assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)"); + } +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index fd6824b74a..542a3e8c41 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "30c3e72f47489d707c1c5657e16459dd362b5f2d"; +const REV: &str = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 2a4ae4d927..8d769292cd 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -364,10 +364,107 @@ pub fn run() -> Result<Vec<Shard>, String> { Ok(shards) } +/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's +/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one, +/// a value that is not a number, a count other than the number of shards, or a shard out of range +/// is an error. +pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> { + let (shard, count) = match (shard, count) { + (None, None) => return Ok(None), + (Some(shard), Some(count)) => (shard, count), + _ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()), + }; + let number = + |key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) }; + let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?); + if count != GROUPS.len() { + return Err(format!( + "ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", + GROUPS.len() + )); + } + if !(1..=count).contains(&shard) { + return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}")); + } + Ok(Some(shard - 1)) +} + +/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it +/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it +/// builds that shard alone, and without it every shard. A split's later parts build nothing: they +/// build the same tests as part 1, whose leg puts them in the cache. +pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) { + let mut tests = Vec::new(); + let mut checks = false; + for (i, shard) in shards.iter().enumerate() { + if only.is_some_and(|k| k != i) { + continue; + } + match shard { + Shard::Checks => checks = true, + Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {} + Shard::Tests(..) => tests.push(i), + } + } + (tests, checks) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn warm_builds_every_shard_unless_the_gate_names_one() { + let n = GROUPS.len().to_string(); + assert_eq!(warm_only(None, None), Ok(None)); + assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0))); + assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1))); + for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] { + assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}"); + } + let past = (GROUPS.len() + 1).to_string(); + assert!(warm_only(Some(&past), Some(&n)).is_err()); + assert!(warm_only(Some("1"), Some(&past)).is_err()); + } + + #[test] + fn warm_builds_each_shard_of_the_plan() { + let ws = [m("a"), m("b")]; + let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(warm_plan(&shards, None), (vec![0, 2], true)); + assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false)); + assert_eq!(warm_plan(&shards, Some(1)), (vec![], false)); + assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false)); + assert_eq!(warm_plan(&shards, Some(3)), (vec![], true)); + // The real plan: every leg the gate names builds its own shard (a split's later part + // builds nothing), and the legs together, like a full warm, build every crate's tests + // once and the checks. + let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap(); + let mut owned: Vec<&str> = real.iter().flat_map(owners).collect(); + owned.sort_unstable(); + let (mut legs, mut leg_checks) = (Vec::new(), 0); + for i in 0..GROUPS.len() { + let n = GROUPS.len().to_string(); + let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap(); + let (tests, checks) = warm_plan(&real, only); + let want = match &real[i] { + Shard::Checks => (vec![], true), + Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false), + Shard::Tests(..) => (vec![i], false), + }; + assert_eq!((tests.clone(), checks), want, "shard {}", i + 1); + legs.extend(tests); + leg_checks += usize::from(checks); + } + let (tests, checks) = warm_plan(&real, None); + assert!(checks); + assert_eq!(leg_checks, 1); + assert_eq!(tests, legs); + let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect(); + built.sort_unstable(); + assert_eq!(built, owned); + } + fn m(name: &str) -> Member { Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true } } diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..c95215cd4c --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,7890 @@ +//! `cargo xtask test-lint`: tests that a wrong result can pass, in the tests a change touches. +//! +//! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, +//! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): +//! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, +//! count, first item or `any` in an assertion's condition or compared operands, nor takes a +//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! collection (negated `.all(…)`, including `== false`, and predicates saying that no item +//! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier +//! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver +//! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array +//! literal or `vec![…]` guards only that receiver, and so does an assertion on a local bound to a +//! count, length or emptiness check. Collections that cannot be empty are also left out: +//! non-empty array literals; plain locals of the test bound to an array type of a positive length, +//! to a non-empty array literal or `vec![…]` or a literal range (lengths and repetition counts may +//! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, +//! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later +//! code may shrink or replace them; and fields the file declares only as arrays of a positive +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change +//! anywhere in the test counts as a change to the hit; +//! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the +//! test calls no asserting helper; +//! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that +//! expression calls nothing with arguments (two calls with arguments check determinism) and no +//! method that returns the next value each time ([`ADVANCING`], such as `next`); +//! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no +//! output, with a status check in any condition or compared operand of a standard assertion; +//! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, +//! and no `#[should_panic]`; +//! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value +//! from the code under test. Left out: a return after an assertion in its block, one whose +//! statement or line has a comment or a printed note saying why, and guards on files, fonts, +//! corpora, environment variables, the platform or a child process; +//! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; +//! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the +//! file's code sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments, +//! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable +//! reads do not; +//! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it. Left +//! out: the pause of a `while` or `loop` that checks a condition (its condition or body calls a +//! function or method besides reading the clock), also under an `if` or `match` inside that +//! loop, and the delay inside a closure passed to `spawn` whose thread handle the test drops; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, +//! `read_to_string` of a path with a `.rs` literal, or a walk that keeps files ending in `.rs`), +//! outside the source audits in [`SOURCE_AUDITS`]; +//! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`, +//! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`, +//! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of +//! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, +//! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! * `mirror`: `assert_eq!(f(a), f(b) <op> …)`, where the expected side derives its value from a +//! second call of the same function (same path) with arithmetic, so a fault in `f` moves both +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same +//! arithmetic on both sides and two reads that differ only in the entry they name (a string or +//! integer literal, a local or an indexed element); +//! * `constant-echo`: every assertion of the test compares only constants, literals and enum +//! variants; +//! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the +//! test bound (in scope) to such values, so nothing the code under test returned is checked; +//! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod` +//! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on +//! x86_64, and Windows for the app and the UI crate's print tests). A test that still builds on +//! macOS or Windows is listed without failing the check: it tests code or behavior of that +//! platform and runs locally there; +//! * `exact-pixel`: in a file that uses egui, an assertion that a screen rect (an identifier `rect`, +//! `rect_…` or `…_rect`, whole or through a corner, edge or size) equals numbers written out. +//! +//! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, +//! or a test function. +//! +//! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) +//! that asserts, panics or calls one that does (every one of that name, when there are several), +//! or a call whose name starts with `assert`, `check`, `verify`, `ensure` or `expect_`. +//! +//! `// test-lint: allow <rule> <reason>` exempts the line it is on and the line below it; for the +//! rules about a whole test it can be on any line from the line above the test attribute to the +//! `fn` line. An allow without a reason exempts nothing. +//! +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, +//! `reads-source` and `never-run` (except a test that builds on macOS or Windows) in the lines and +//! tests changed since a base, and lists the other rules' hits there without failing. The base is `--base <rev>` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge +//! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as +//! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the +//! workspace by crate and rule, and does not fail. + +use std::cell::{OnceCell, RefCell}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::Path; +use std::process::Command; + +/// Test files that read Rust source on purpose: they audit the source tree. +pub const SOURCE_AUDITS: &[&str] = &[ + "crates/plugins/tests/grant_sites.rs", + "crates/ui-egui/src/i18n/tests.rs", + "crates/ui-egui/src/icons.rs", + "crates/eps/src/import/tests_generators.rs", +]; + +/// Variables the shared gate workflow and its setup action set on every leg, besides those named +/// in `.github/workflows/*.yml`. +const SHARED_GATE_ENV: &[&str] = + &["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "GATE_SHARD", "GATE_SHARDS", "NEXTEST_PARTITION", "NEXTEST_ARCHIVE_FILE"]; + +/// Variables the runner, the operating system or cargo set. +const SYSTEM_ENV: &[&str] = &[ + "HOME", + "PATH", + "USER", + "USERNAME", + "LOGNAME", + "TMPDIR", + "TEMP", + "TMP", + "APPDATA", + "LOCALAPPDATA", + "USERPROFILE", + "PROGRAMDATA", + "PROGRAMFILES", + "WINDIR", + "SYSTEMROOT", + "CI", + "LANG", + "SHELL", + "PWD", + "OUT_DIR", +]; +const SYSTEM_ENV_PREFIXES: &[&str] = &["CARGO_", "NEXTEST", "RUST", "GITHUB_", "RUNNER_", "XDG_"]; + +/// Larger source files are refused rather than read. +const MAX_FILE: u64 = 16 << 20; + +/// The marker of an exemption comment. +const ALLOW: &str = "test-lint: allow "; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Rule { + AllUnguarded, + OnlyWeak, + SelfCompare, + ExitStatusOnly, + NoAssertion, + EarlyReturn, + IgnoreWithoutReason, + EnvGateUnset, + Sleep, + ReadsSource, + Census, + Mirror, + ConstantEcho, + FixtureOnly, + NeverRun, + ExactPixel, +} + +impl Rule { + pub const ALL: [Rule; 16] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + Rule::Census, + Rule::Mirror, + Rule::ConstantEcho, + Rule::FixtureOnly, + Rule::NeverRun, + Rule::ExactPixel, + ]; + + pub fn id(self) -> &'static str { + match self { + Rule::AllUnguarded => "all-unguarded", + Rule::OnlyWeak => "only-weak", + Rule::SelfCompare => "self-compare", + Rule::ExitStatusOnly => "exit-status-only", + Rule::NoAssertion => "no-assertion", + Rule::EarlyReturn => "early-return", + Rule::IgnoreWithoutReason => "ignore-without-reason", + Rule::EnvGateUnset => "env-gate-unset", + Rule::Sleep => "sleep", + Rule::ReadsSource => "reads-source", + Rule::Census => "census", + Rule::Mirror => "mirror", + Rule::ConstantEcho => "constant-echo", + Rule::FixtureOnly => "fixture-only", + Rule::NeverRun => "never-run", + Rule::ExactPixel => "exact-pixel", + } + } + + fn advice(self) -> &'static str { + match self { + Rule::AllUnguarded => "also assert the expected length (or that the collection is not empty)", + Rule::OnlyWeak => "assert the value itself (assert_eq! on the result), not only that there is one", + Rule::SelfCompare => "compare with an expected value written out, or with a second, independent computation", + Rule::ExitStatusOnly => "also check the output (stdout, stderr or the files written)", + Rule::NoAssertion => "assert what the code returns or changes", + Rule::EarlyReturn => "assert the condition instead of returning, so a wrong value fails the test", + Rule::IgnoreWithoutReason => "write #[ignore = \"why\"]", + Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it", + Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", + Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", + Rule::Census => "test one or a few representative entries and the edge cases (or generate inputs), not every entry of the table", + Rule::Mirror => "compare with an expected value written out, not with a second call of the same function", + Rule::ConstantEcho => "assert what the code under test returns, not a constant or literal the test or crate states", + Rule::FixtureOnly => "assert on what the code under test returns or changes, not on the input the test built", + Rule::NeverRun => "make the test build on a target CI runs (Linux, FreeBSD), or run it in a CI leg for its target", + Rule::ExactPixel => { + "assert relationships (inside its container, not overlapping, order, gap at least a spacing token), not a rect equal to numbers" + } + } + } + + /// Whether a hit on a changed line fails the command. The other rules only report. + pub fn fails(self) -> bool { + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) + } + + fn from_id(id: &str) -> Option<Rule> { + Rule::ALL.into_iter().find(|r| r.id() == id) + } +} + +/// A rule broken in a file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Hit { + pub path: String, + /// 1-based: the line of the finding, or of `fn` for a rule about a whole test. + pub line: usize, + pub rule: Rule, + /// The test it is in; empty for test code outside a test function. + pub test: String, + pub note: String, + /// The first and last line of what the hit covers: the test, from its attribute to its closing + /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for + /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span + /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply + /// only near `line`. + pub first: usize, + pub last: usize, + /// Lines outside `first..=last` that also count as changes to the hit: the enclosing `cfg` + /// attributes of a `never-run` test, and the loop or spawn statement around a `sleep`. An + /// allow comment there does not exempt it. + pub gates: Vec<usize>, + /// A `never-run` hit on a test that builds on macOS or Windows, which CI does not test on: it is + /// listed with the report-only rules. + pub report_only: bool, +} + +impl Hit { + /// Whether the hit fails the check when it is on a changed line. + fn fails(&self) -> bool { + self.rule.fails() && !self.report_only + } + + fn show(&self) -> String { + let test = if self.test.is_empty() { String::new() } else { format!(" `{}`", self.test) }; + format!("{}:{}: [{}]{test}: {}", self.path, self.line, self.rule.id(), self.note) + } +} + +/// What the rules need beyond the file: asserting helper names by crate, the variables CI sets, and +/// the `cfg` predicates each file's module inherits from the `mod` declarations above it. +#[derive(Default)] +pub struct Ctx { + pub helpers: HashMap<String, HashSet<String>>, + pub ci_env: HashSet<String>, + pub module_cfgs: HashMap<String, Vec<String>>, +} + +/// Whether a parent file's changed lines touch a `mod` declaration or `cfg` attribute that `gates` +/// came from. +fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap<String, Option<BTreeSet<usize>>>) -> bool { + gates + .into_iter() + .flat_map(|g| &g.sources) + .any(|(parent, lines)| changed.get(parent).is_some_and(|c| c.as_ref().is_none_or(|set| lines.iter().any(|l| set.contains(l))))) +} + +/// Whether a change touches the declarations that gate the module file `path` now +/// ([`gate_changed`]), or any file that declared it at the base: an edit there can remove a way for +/// its tests to run, and the base lines may no longer match. +fn route_gate_changed( + path: &str, + gates: Option<&Gates>, + base_gates: Option<&Gates>, + base_overrides: &Overrides, + changed: &BTreeMap<String, Option<BTreeSet<usize>>>, +) -> bool { + gate_changed(gates, changed) + || base_gates.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) + || base_overrides.get(path).is_some_and(|routes| routes.iter().any(|(parent, _)| changed.contains_key(parent))) +} + +/// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. +fn read_small(root: &Path, path: &str) -> Option<String> { + let full = root.join(path); + (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() +} + +/// The scanned files of the tree at `base`, or `None` when Git cannot list it. +fn base_files(root: &Path, base: &str) -> Option<Vec<String>> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", base]).ok()?; + Some(list.split('\0').filter(|p| !p.is_empty() && is_scanned(p)).map(str::to_owned).collect()) +} + +/// Cache successful and missing reads for one source tree. +fn cached_read(read: impl Fn(&str) -> Option<String>) -> impl Fn(&str) -> Option<String> { + let cache = RefCell::new(HashMap::<String, Option<String>>::new()); + move |path| cache.borrow_mut().entry(path.to_owned()).or_insert_with(|| read(path)).clone() +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let read_work = cached_read(|p| read_small(root, p)); + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec<String> = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let overrides = with_root_routes(path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))), &files); + let module_cfgs = module_cfgs(&files, &read_work, &overrides); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; + let hits: Vec<Hit> = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); + print!("{}", report(&hits, sources.len())); + return Ok(()); + } + let base = resolve_base(root, opts.base)?; + let changed = changed_lines(root, &base)?; + let changed: BTreeMap<String, Option<BTreeSet<usize>>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let crates: BTreeSet<String> = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); + let helper_files: Vec<String> = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); + let present: Vec<String> = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + // Files that load a module through `#[path]`, found with `git grep` (untracked files included) + // instead of reading the tree, and the target roots beside a shared `tests/<dir>/mod.rs`. + let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); + let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + // The base's target roots come from the base tree: a root the change deleted still loaded the + // shared module beside it. + let base_overrides = + with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &base_files(root, &base).unwrap_or_else(|| files.clone())); + // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. + // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. + let seeds: Vec<String> = changed.keys().cloned().collect(); + let below: Vec<String> = + descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); + let gated: Vec<String> = present.iter().chain(&below).cloned().collect(); + let gates = module_gates(&gated, &read_work, &overrides); + let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; + // The gates the parent declarations gave at the base: a parent edit counts against a child's + // test only when the test ran in CI before it. + let base_gates = module_gates(&gated, &read_base, &base_overrides); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; + // The base's `never-run` hits on the file as it was at the base (the current source when the + // file is new or moved), computed once per file on its first parent-attributed hit. + let base_off: RefCell<HashMap<String, (String, Vec<Hit>)>> = RefCell::new(HashMap::new()); + let newly_off = |path: &str, src: &str, hit: &Hit| { + let mut cache = base_off.borrow_mut(); + let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| { + let base_src = read_base(path).unwrap_or_else(|| src.to_owned()); + let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + (base_src, off) + }); + !already_off(off, base_src, src, hit) + }; + let (mut counted, mut older) = (vec![], 0usize); + for (path, src) in read_all(root, &present)? { + let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); + for hit in lint_file(&path, &src, &ctx) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) + || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) + { + counted.push(hit); + } else { + older += 1; + } + } + } + for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + let Some(src) = read_work(path) else { continue }; + counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); + } + finish(&counted, older, present.len(), &base) +} + +/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place +/// among the tests of that name in those modules, so lines that moved still match and tests of one +/// name in different inline modules stay apart, even when a change removes one of the modules. +fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { + let place = test_place(src, &hit.test, hit.line); + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), + None => h.line == hit.line, + }) +} + +/// The inline modules around the test `name` whose `fn` is on `line` in `src` (outermost first), +/// and its index among the tests of that name in the same modules. +fn test_place(src: &str, name: &str, line: usize) -> Option<(Vec<String>, usize)> { + let lines = Lines::new(src); + let m = mask(src); + let named: Vec<(Vec<String>, usize)> = + tests_in(&m).iter().filter(|t| t.name == name).map(|t| (inline_modules(&m, t.fn_at), lines.of(t.fn_at))).collect(); + let (scope, _) = named.iter().find(|(_, l)| *l == line)?; + let index = named.iter().filter(|(s, _)| s == scope).position(|(_, l)| *l == line)?; + Some((scope.clone(), index)) +} + +/// The names of the inline `mod <name> { … }` blocks around `at` in the masked text `m`, outermost +/// first. +fn inline_modules(m: &[u8], at: usize) -> Vec<String> { + let mut open: Vec<Option<String>> = vec![]; + for (i, &c) in m.iter().enumerate().take(at) { + match c { + b'{' => { + let head = m[..i].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + let keyword = name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident); + open.push(keyword.then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())); + } + b'}' => { + open.pop(); + } + _ => {} + } + } + open.into_iter().flatten().collect() +} + +/// The directory holding the modules that the file `p` declares by name: its own directory for +/// `mod.rs`, `lib.rs`, `main.rs` and crate roots ([`owns_its_dir`]), and the directory named after +/// it otherwise. +fn module_dir(p: &str) -> String { + let dir = p.rsplit_once('/').map_or("", |(d, _)| d); + if owns_its_dir(p) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } +} + +/// The files of `files` that the files `start` load, directly or through modules in between: the +/// files under their module directories and the files their current or base `#[path]` declarations load. +/// A file loaded through `#[path]` also loads the modules it declares by name from its own directory +/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the +/// declarations a change removed, through `read_base`. +fn descendants( + start: &[String], + files: &[String], + overrides: &Overrides, + base_overrides: &Overrides, + read: &dyn Fn(&str) -> Option<String>, + read_base: &dyn Fn(&str) -> Option<String>, +) -> Vec<String> { + let mut seen: BTreeSet<String> = start.iter().cloned().collect(); + let mut frontier: Vec<String> = start.to_vec(); + let mut out = vec![]; + while !frontier.is_empty() { + let beside = |p: &String| -> Vec<String> { + if owns_its_dir(p) || !(overrides.contains_key(p) || base_overrides.contains_key(p)) { + return vec![]; + } + let dir = p.rsplit_once('/').map_or("", |(d, _)| d); + [read(p), read_base(p)] + .into_iter() + .flatten() + .flat_map(|src| declared_names(&src)) + .flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]) + .collect() + }; + let dirs: Vec<String> = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect(); + let next: Vec<String> = files + .iter() + .filter(|p| !seen.contains(*p)) + .filter(|p| { + dirs.iter().any(|d| p.starts_with(d.as_str())) + || overrides.get(*p).into_iter().chain(base_overrides.get(*p)).flatten().any(|(parent, _)| frontier.contains(parent)) + }) + .cloned() + .collect(); + seen.extend(next.iter().cloned()); + out.extend(next.iter().cloned()); + frontier = next; + } + out +} + +/// The names of the modules `src` declares, by file (`mod child;`) or inline (`mod platform { … }`). +fn declared_names(src: &str) -> Vec<String> { + let m = mask(src); + words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + (end > start && matches!(m.get(skip_ws(&m, end)), Some(b';' | b'{'))).then(|| String::from_utf8_lossy(&m[start..end]).into_owned()) + }) + .collect() +} + +/// The command line: `--all`, `--base <rev>`. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option<String>, +} + +impl Options { + fn parse(args: &[&str]) -> Result<Options, String> { + let mut opts = Options::default(); + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--all" if !opts.all => opts.all = true, + "--base" if opts.base.is_none() => match it.next() { + Some(rev) if !rev.is_empty() && !rev.starts_with('-') => opts.base = Some((*rev).to_owned()), + _ => return Err("test-lint: --base takes a revision".into()), + }, + _ => return Err(format!("test-lint: unexpected argument `{arg}` (usage: cargo xtask test-lint [--all] [--base <rev>])")), + } + } + if opts.all && opts.base.is_some() { + return Err("test-lint: --all checks every file and takes no --base".into()); + } + Ok(opts) + } +} + +fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { + let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; + let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.fails()); + if !reported.is_empty() { + println!( + "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + reported.len(), + listing(&reported).join("\n ") + ); + } + if failing.is_empty() { + println!("test-lint: no failing hits in the changed lines of {files} Rust file(s) since {base}{older}"); + return Ok(()); + } + Err(format!( + "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW}<rule> <reason>`):\n {}", + failing.len(), + listing(&failing).join("\n ") + )) +} + +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec<String> { + let mut out: Vec<String> = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet<Rule> = hits.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + out +} + +/// `--all`: counts by crate and rule, then every hit. +fn report(hits: &[Hit], files: usize) -> String { + let mut by_crate: BTreeMap<String, BTreeMap<Rule, usize>> = BTreeMap::new(); + for h in hits { + *by_crate.entry(crate_of(&h.path)).or_default().entry(h.rule).or_default() += 1; + } + let mut out = format!("test-lint --all: {} hit(s) in {files} Rust file(s)\n\nby rule:\n", hits.len()); + for rule in Rule::ALL { + out += &format!(" {:<22} {}\n", rule.id(), hits.iter().filter(|h| h.rule == rule).count()); + } + out += "\nby crate:\n"; + for (krate, rules) in &by_crate { + let list: Vec<String> = rules.iter().map(|(r, n)| format!("{} {n}", r.id())).collect(); + out += &format!(" {krate}: {}\n", list.join(", ")); + } + out += "\nhits:\n"; + for h in hits { + out += &format!(" {}\n", h.show()); + } + out +} + +/// Rust files the lint reads. +fn is_scanned(path: &str) -> bool { + path.ends_with(".rs") && ["crates/", "apps/", "xtask/"].iter().any(|d| path.starts_with(d)) +} + +/// `crates/<name>` or `apps/<name>` for a file in one, else its first path component. +fn crate_of(path: &str) -> String { + let parts: Vec<&str> = path.split('/').collect(); + match parts.as_slice() { + [top @ ("crates" | "apps"), name, _, ..] => format!("{top}/{name}"), + [first, ..] => (*first).to_owned(), + [] => String::new(), + } +} + +fn read_all(root: &Path, paths: &[String]) -> Result<Vec<(String, String)>, String> { + paths + .iter() + .map(|p| { + let full = root.join(p); + let len = std::fs::metadata(&full).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_FILE { + return Err(format!("{p}: {len} bytes, over test-lint's limit of {MAX_FILE}")); + } + Ok((p.clone(), std::fs::read_to_string(&full).map_err(|e| format!("{p}: {e}"))?)) + }) + .collect() +} + +// ---- Git: the base and the changed lines ---- + +fn git(root: &Path, args: &[&str]) -> Result<String, String> { + let out = Command::new("git").current_dir(root).args(args).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +fn resolve_base(root: &Path, explicit: Option<String>) -> Result<String, String> { + if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { + return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) + .map_err(|_| format!("test-lint: base `{rev}` is not a commit")); + } + if std::env::var_os("GITHUB_ACTIONS").is_some() { + if let Ok(parent) = git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) { + return Ok(parent); + } + let head = git(root, &["rev-parse", "HEAD"])?; + git(root, &["fetch", "--no-tags", "--quiet", "--depth=2", "origin", &head])?; + return git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) + .map_err(|_| "test-lint: HEAD has no parent to compare with (set TEST_LINT_BASE)".into()); + } + for main in ["upstream/main", "origin/main"] { + if let Ok(base) = git(root, &["merge-base", "HEAD", main]) { + return Ok(base); + } + } + Err("test-lint: no upstream/main or origin/main to compare with; pass --base <rev> or set TEST_LINT_BASE".into()) +} + +/// The changed files since `base` with their changed lines (new numbering); `None` for a file that +/// is new or untracked. A pure deletion marks the lines before and after it, or line 1 at the top +/// of the file. +fn changed_lines(root: &Path, base: &str) -> Result<BTreeMap<String, Option<BTreeSet<usize>>>, String> { + let diff = git( + root, + &[ + "-c", + "core.quotepath=off", + "diff", + "-U0", + "--inter-hunk-context=0", + "--no-color", + "--no-ext-diff", + // A rename shows as a deletion and an addition, so both paths count as changed. + "--no-renames", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + "--", + "*.rs", + ], + )?; + let mut out = parse_diff(&diff); + for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { + out.insert(path.to_owned(), None); + } + Ok(out) +} + +/// The changed new-side lines in each file. A pure deletion includes its anchor and the following +/// line, or just line 1 when the anchor is 0. +fn parse_diff(diff: &str) -> BTreeMap<String, Option<BTreeSet<usize>>> { + let mut out: BTreeMap<String, Option<BTreeSet<usize>>> = BTreeMap::new(); + let mut current: Option<String> = None; + // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. + let (mut header, mut new_file) = (false, false); + let mut old: Option<String> = None; + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file, old) = (true, false, None); + } else if header && line.starts_with("new file mode") { + new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); + } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { + current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); + if let Some(p) = ¤t { + out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } else if let Some(p) = old.take().filter(|_| path == "/dev/null") { + // A deleted file is kept, wholly changed: it may have been a route that loaded a module. + out.insert(p, None); + } + } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { + header = false; + if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { + if count == 0 { + lines.extend(start.max(1)..=start.saturating_add(1)); + } else { + lines.extend(start..start + count); + } + } + } + } + out +} + +/// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a +/// path with a quote, a backslash or a control character as a C-style quoted string. +fn patch_path(label: &str) -> Option<String> { + let label = label.strip_suffix('\t').unwrap_or(label); + let Some(quoted) = label.strip_prefix('"') else { return Some(label.to_owned()) }; + let body = quoted.strip_suffix('"')?.as_bytes(); + let (mut out, mut i) = (Vec::with_capacity(body.len()), 0); + while i < body.len() { + if body[i] != b'\\' { + out.push(body[i]); + i += 1; + continue; + } + let c = *body.get(i + 1)?; + let octal = body.get(i + 1..i + 4).filter(|d| d.iter().all(|c| (b'0'..=b'7').contains(c))); + if let Some(digits) = octal { + out.push(digits.iter().fold(0u8, |n, d| n.wrapping_mul(8).wrapping_add(d - b'0'))); + i += 4; + continue; + } + out.push(match c { + b'a' => 7, + b'b' => 8, + b't' => b'\t', + b'n' => b'\n', + b'v' => 11, + b'f' => 12, + b'r' => b'\r', + other => other, + }); + i += 2; + } + String::from_utf8(out).ok() +} + +/// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 +/// and sits between lines c and c + 1; c = 0 places it before line 1. +fn hunk_range(hunk: &str) -> Option<(usize, usize)> { + let new = hunk.split_whitespace().find(|w| w.starts_with('+'))?.trim_start_matches('+'); + match new.split_once(',') { + Some((s, c)) => Some((s.parse().ok()?, c.parse().ok()?)), + None => Some((new.parse().ok()?, 1)), + } +} + +/// Whether `hit` covers a changed line (`None`: the whole file is new). +fn touches(hit: &Hit, changed: Option<&BTreeSet<usize>>) -> bool { + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some() || hit.gates.iter().any(|l| lines.contains(l))) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result<HashSet<String>, String> { + let mut names: HashSet<String> = SHARED_GATE_ENV.iter().map(|s| (*s).to_owned()).collect(); + for path in files.iter().filter(|p| p.starts_with(".github/workflows/") && (p.ends_with(".yml") || p.ends_with(".yaml"))) { + let text = std::fs::read_to_string(root.join(path)).map_err(|e| format!("{path}: {e}"))?; + names.extend(upper_words(&text)); + } + Ok(names) +} + +/// Workflow mapping keys and assignments with capitalized environment variable names. +fn upper_words(text: &str) -> impl Iterator<Item = String> + '_ { + text.lines().flat_map(|line| { + let line = workflow_code(line); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = + start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); + let from = at - name.len(); + let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) + }); + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + }) +} + +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line +/// that does not write to `$GITHUB_ENV`. +fn printed(line: &str, from: usize) -> bool { + let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); + let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); + prints && !line.contains("GITHUB_ENV") +} + +fn env_assignment_name(name: &str) -> bool { + name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') +} + +/// Removes comment text outside quotes from a workflow line. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped) = (None, false); + for (at, c) in line.char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => return &line[..at], + _ => {} + } + } + } + line +} + +fn set_by_system(name: &str) -> bool { + SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) +} + +// ---- Lexing ---- + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// `src` with the text of comments and of string and character literals replaced by spaces (line +/// breaks and quotes kept), at the same byte offsets. +fn mask(src: &str) -> Vec<u8> { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec<u8> { + mask_parts(src, comments, true) +} + +/// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. +fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec<u8> { + let b = src.as_bytes(); + let mut out = b.to_vec(); + let mut i = 0; + while i < b.len() { + let next = match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + let end = find(b, b"\n", i).unwrap_or(b.len()); + if comments { + blank(&mut out, i, end); + } + end + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = block_comment_end(b, i); + if comments { + blank(&mut out, i, end); + } + end + } + b'"' => { + let end = string_end(b, i + 1); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1)); + } + end + } + b'\'' => { + let end = after_char_or_lifetime(src, i); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1).max(i + 1)); + } + end + } + c if c.is_ascii_alphabetic() || c == b'_' => after_ident(b, &mut out, i, literals), + _ => i + 1, + }; + i = next.max(i + 1); + } + out +} + +fn blank(out: &mut [u8], from: usize, to: usize) { + for c in out.iter_mut().take(to).skip(from) { + if *c != b'\n' { + *c = b' '; + } + } +} + +fn block_comment_end(b: &[u8], mut i: usize) -> usize { + let mut nest = 0usize; + while i < b.len() { + if b[i..].starts_with(b"/*") { + nest += 1; + i += 2; + } else if b[i..].starts_with(b"*/") { + nest = nest.saturating_sub(1); + i += 2; + if nest == 0 { + return i; + } + } else { + i += 1; + } + } + b.len() +} + +/// The index after the closing quote of a `"…"` literal whose body starts at `i`. +fn string_end(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + (i + 1).min(b.len()) +} + +/// The index after a char literal (`'x'`, `'\n'`, `'\u{…}'`) at `i`, or after the quote of a +/// lifetime or label. +fn after_char_or_lifetime(src: &str, i: usize) -> usize { + let b = src.as_bytes(); + if b.get(i + 1) == Some(&b'\\') { + let close = (i + 3..b.len()).find(|&j| b[j] == b'\'').unwrap_or(b.len()); + return (close + 1).min(b.len()); + } + match src.get(i + 1..).and_then(|s| s.chars().next()) { + Some(c) if b.get(i + 1 + c.len_utf8()) == Some(&b'\'') => i + 2 + c.len_utf8(), + _ => i + 1, + } +} + +/// Skips the identifier at `start`; a raw string prefix (`r`, `br`, `cr`) also skips the raw +/// string after it and blanks its contents when `literals` is true. +fn after_ident(b: &[u8], out: &mut [u8], start: usize, literals: bool) -> usize { + let mut i = start; + while i < b.len() && is_ident(b[i]) { + i += 1; + } + if start > 0 && is_ident(b[start - 1]) { + return i; + } + let hashes = b[i..].iter().take_while(|&&h| h == b'#').count(); + if !matches!(&b[start..i], b"r" | b"br" | b"cr") || b.get(i + hashes) != Some(&b'"') { + return i; + } + let body = i + hashes + 1; + let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(b, &close, body).unwrap_or(b.len()); + if literals { + blank(out, body, end); + } + (end + close.len()).min(b.len()) +} + +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> { + if needle.is_empty() || from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle, 0).is_some() +} + +fn skip_ws(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + i +} + +/// Every start of `word` in `b[from..to]` with no identifier character on either side. +fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec<usize> { + let mut out = vec![]; + let mut i = from; + while let Some(at) = find(&b[..to.min(b.len())], word, i) { + let before = at.checked_sub(1).and_then(|j| b.get(j)).copied().is_some_and(is_ident); + let after = b.get(at + word.len()).copied().is_some_and(is_ident); + if !before && !after { + out.push(at); + } + i = at + 1; + } + out +} + +/// The index of the bracket closing the one at `open`. +fn matching(m: &[u8], open: usize) -> Option<usize> { + let (o, c) = match m.get(open)? { + b'(' => (b'(', b')'), + b'[' => (b'[', b']'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0usize; + for (j, &ch) in m.iter().enumerate().skip(open) { + if ch == o { + depth += 1; + } else if ch == c { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The ranges of the top-level comma-separated parts of `m[from..to]`. +fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + let (mut out, mut depth, mut start) = (vec![], 0i32, from); + let mut angles = 0usize; + for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + match ch { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'>' if angles > 0 => angles -= 1, + b',' if depth == 0 && angles == 0 => { + out.push((start, j)); + start = j + 1; + } + _ => {} + } + } + if m[start..to].iter().any(|c| !c.is_ascii_whitespace()) { + out.push((start, to)); + } + out +} + +/// `b` without whitespace. +fn norm(b: &[u8]) -> String { + String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::<Vec<u8>>()).into_owned() +} + +/// [`norm`], except that whitespace between two identifier characters becomes one space, so +/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`]. +fn norm_words(b: &[u8]) -> String { + let mut out = vec![]; + let mut gap = false; + for &c in b { + if c.is_ascii_whitespace() { + gap = true; + continue; + } + if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) { + out.push(b' '); + } + gap = false; + out.push(c); + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec<usize>); + +impl Lines { + fn new(src: &str) -> Lines { + Lines(std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()) + } + + fn of(&self, pos: usize) -> usize { + self.0.partition_point(|&s| s <= pos) + } +} + +// ---- Tests and calls ---- + +/// A test function: its name, the offsets of its first attribute and `fn`, and its body's braces. +#[derive(Debug)] +struct TestFn { + name: String, + /// The first attribute of the function (`#[should_panic]` can come before `#[test]`). + attr: usize, + fn_at: usize, + open: usize, + close: usize, +} + +fn is_test_attr(path: &[u8]) -> bool { + matches!(path, b"test" | b"wasm_bindgen_test" | b"test_case") || path.ends_with(b"::test") || path.ends_with(b"::test_case") +} + +/// The test functions of masked source `m`. +fn tests_in(m: &[u8]) -> Vec<TestFn> { + let mut out: Vec<TestFn> = vec![]; + let mut i = 0; + while let Some(at) = find(m, b"#[", i) { + i = at + 2; + let start = skip_ws(m, at + 2); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if !is_test_attr(&m[start..end]) || !matches!(m.get(skip_ws(m, end)), Some(b']' | b'(')) { + continue; + } + let Some(t) = fn_after(m, at, end) else { continue }; + if out.iter().any(|o| o.fn_at == t.fn_at) { + continue; + } + i = t.open; + out.push(t); + } + out +} + +/// The function an attribute at `attr` (ending at `from`) belongs to. +fn fn_after(m: &[u8], attr: usize, from: usize) -> Option<TestFn> { + // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). + let mut from = from.max(matching(m, attr + 1)? + 1); + while m[skip_ws(m, from)..].starts_with(b"#[") { + from = matching(m, skip_ws(m, from) + 1)? + 1; + } + let limit = (from + 800).min(m.len()); + let fn_at = *words(m, b"fn", from, limit).first()?; + if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { + return None; + } + let name_start = skip_ws(m, fn_at + 2); + // Identifiers may hold non-ASCII letters (`échec`); their UTF-8 bytes are all 0x80 or above. + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); + if name_end == name_start { + return None; + } + let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + // The item starts after the previous item or block opening; comments before it are masked. + // Inner attributes (`#![…]`) there belong to the enclosing module or crate. + let mut item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + while m[skip_ws(m, item)..].starts_with(b"#![") && skip_ws(m, item) < attr { + item = matching(m, skip_ws(m, item) + 2)? + 1; + } + let attr = skip_ws(m, item).min(attr); + Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) +} + +/// A macro call in a test: its name, offset and argument ranges. +struct MacroCall { + name: String, + at: usize, + args: Vec<(usize, usize)>, +} + +/// The macro calls (`name!(…)`, `name![…]`, `name!{…}`) in `m[from..to]`. +fn macro_calls(m: &[u8], from: usize, to: usize) -> Vec<MacroCall> { + let mut out = vec![]; + let mut i = from; + while let Some(bang) = find(&m[..to], b"!", i) { + i = bang + 1; + let start = (from..bang).rev().take_while(|&j| is_ident(m[j])).last().unwrap_or(bang); + let open = skip_ws(m, bang + 1); + if start == bang || start.checked_sub(1).is_some_and(|j| is_ident(m[j])) || !matches!(m.get(open), Some(b'(' | b'[' | b'{')) { + continue; + } + let Some(close) = matching(m, open).filter(|&c| c < to) else { continue }; + out.push(MacroCall { name: String::from_utf8_lossy(&m[start..bang]).into_owned(), at: start, args: split_args(m, open + 1, close) }); + } + out +} + +fn is_assert_macro(name: &str) -> bool { + ["assert", "debug_assert", "prop_assert"].iter().any(|p| name.starts_with(p)) +} + +const KEYWORDS: &[&str] = &["if", "while", "match", "for", "loop", "return", "fn", "in", "as", "let", "else", "move", "Some", "Ok", "Err"]; + +/// Names that helper detection ignores: too common to tell a helper from the code under test. +const COMMON: &[&str] = &[ + "new", "default", "from", "into", "get", "set", "run", "apply", "build", "make", "open", "load", "save", "parse", "read", "write", "draw", + "render", "len", "clone", "push", "vec", "format", "json", "Box", "Arc", "Vec", "String", "main", +]; + +/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods +/// (`.name(`), including calls with turbofish arguments, and macros (`name!`). +fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(_, name, method)| (name, method)).collect() +} + +/// [`calls`] with the index where each name starts. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, String, bool)> { + let m = &m[..to]; + let mut out = vec![]; + let mut i = from; + while i < to { + if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + i += 1; + continue; + } + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let bang = m.get(end) == Some(&b'!'); + let after = skip_ws(m, end + usize::from(bang)); + let after = if bang { after } else { skip_turbofish(m, after) }; + if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { + let name = String::from_utf8_lossy(&m[i..end]).into_owned(); + let method = i > 0 && m[i - 1] == b'.'; + if !KEYWORDS.contains(&name.as_str()) { + out.push((i, if bang { format!("{name}!") } else { name }, method)); + } + } + i = end; + } + out +} + +/// Skips optional `::<…>` arguments and the whitespace after them. +fn skip_turbofish(m: &[u8], at: usize) -> usize { + if !m[at..].starts_with(b"::") { + return at; + } + let open = skip_ws(m, at + 2); + if m.get(open) != Some(&b'<') { + return at; + } + let (mut i, mut depth) = (open + 1, 1usize); + while i < m.len() { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + return skip_ws(m, i + 1); + } + } + b'(' | b'[' | b'{' => i = matching(m, i).unwrap_or(m.len()), + _ => {} + } + i += 1; + } + m.len() +} + +/// Whether `name` (a call in a test) is an asserting helper. +fn is_helper_call(name: &str, method: bool, helpers: &HashSet<String>) -> bool { + let base = name.trim_end_matches('!'); + let named = ["assert", "check", "verify", "ensure", "expect_"].iter().any(|p| base.starts_with(p)); + named || (!method && !COMMON.contains(&base) && helpers.contains(name)) +} + +/// Whether the masked text checks something itself: an assertion, `panic!`, `unwrap_err` or +/// `expect_err`. +fn checks_itself(m: &[u8], from: usize, to: usize) -> bool { + let body = &m[from..to]; + contains(body, b"panic!") || rejects(body) || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) +} + +/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and +/// `crates/testkit`. +fn is_test_file(path: &str) -> bool { + let mut parts = path.split('/').rev(); + let file = parts.next().unwrap_or_default(); + file == "tests.rs" + || file.starts_with("tests_") + || file.ends_with("_tests.rs") + || parts.any(|d| d == "tests" || d == "benches") + || path.starts_with("crates/testkit/") +} + +/// Whether a `cfg` predicate holds only in test builds: `test`, or an `all(…)` with such a +/// predicate among its arguments. +fn cfg_requires_test(pred: &[u8]) -> bool { + let pred: Vec<u8> = pred.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + if pred == b"test" { + return true; + } + let Some(args) = pred.strip_prefix(b"all(").and_then(|a| a.strip_suffix(b")")) else { return false }; + let mut depth = 0usize; + let mut start = 0; + for (i, &c) in args.iter().enumerate() { + match c { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + if cfg_requires_test(&args[start..i]) { + return true; + } + start = i + 1; + } + _ => {} + } + } + cfg_requires_test(&args[start..]) +} + +/// The byte ranges of test code in a file: all of a test file, else each item under a `#[cfg(…)]` +/// that holds only in test builds ([`cfg_requires_test`]) and has a body in the file, and each +/// test function. +fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { + if is_test_file(path) { + return vec![(0, m.len())]; + } + let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); + for at in words(m, b"cfg", 0, m.len()) { + let open = skip_ws(m, at + "cfg".len()); + // Whitespace and comments (masked to spaces) may separate `#`, `[` and `cfg`. + let outer_attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if !outer_attr || m.get(open) != Some(&b'(') { + continue; + } + let Some(close) = matching(m, open) else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') || !cfg_requires_test(&m[open + 1..close]) { + continue; + } + // The item's body: the first `{` before any `;` (`mod tests;` has none here). + let after = end + 1; + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + if let (b'{', Some(close)) = (m[open], matching(m, open)) { + out.push((at, close)); + } + } + out +} + +fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { + regions.iter().any(|&(from, to)| from <= pos && pos <= to) +} + +/// A function or macro in test code: its name (`name!` for a macro), whether it checks something +/// itself, and the names it calls. +type Def = (String, bool, Vec<String>); + +/// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +pub fn asserting_helpers(files: &[(String, String)]) -> HashMap<String, HashSet<String>> { + let mut defs: HashMap<String, Vec<Def>> = HashMap::new(); + for (path, src) in files { + let m = mask(src); + let regions = test_regions(path, &m, &tests_in(&m)); + let crate_defs = defs.entry(crate_of(path)).or_default(); + for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { + if in_regions(®ions, at) { + crate_defs.extend(definition(&m, at)); + } + } + } + let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); + defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() +} + +/// The crate whose test helpers every crate can call. +const TESTKIT: &str = "crates/testkit"; + +/// The names among `defs` that check something, directly or through another of `defs`. Calls do +/// not say which of several functions with one name they reach, so a name counts only when every +/// definition with that name checks. +fn checking<'a>(defs: impl Iterator<Item = &'a Def> + Clone) -> HashSet<String> { + let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); + for d in defs { + by_name.entry(d.0.as_str()).or_default().push(d); + } + let mut known: HashSet<String> = HashSet::new(); + loop { + let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); + let more: Vec<String> = by_name + .iter() + .filter(|(name, same)| !known.contains(**name) && same.iter().all(|d| checks(d))) + .map(|(name, _)| (*name).to_owned()) + .collect(); + if more.is_empty() { + return known; + } + known.extend(more); + } +} + +/// The name, kind (`true` for a macro) and body braces of the `fn` or `macro_rules!` at `at`. +fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { + let is_macro = m[at..].starts_with(b"macro_rules"); + let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); + if is_macro { + start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); + } + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start { + return None; + } + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + Some((&m[start..end], is_macro, open, matching(m, open)?)) +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option<Def> { + let (name, is_macro, open, close) = item_at(m, at)?; + let name = String::from_utf8_lossy(name).into_owned(); + let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) +} + +// ---- The rules ---- + +/// The source, its masked copy and its tests. +struct File<'a> { + path: &'a str, + src: &'a [u8], + m: Vec<u8>, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec<u8>, + lines: Lines, + tests: Vec<TestFn>, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, + /// The `cfg` attributes and the items they cover ([`cfg_spans`]). + cfgs: Vec<CfgSpan>, +} + +impl File<'_> { + fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { + let line = self.lines.of(at); + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, gates: vec![], report_only: false } + } + + fn test_at(&self, pos: usize) -> &str { + self.tests.iter().find(|t| t.open <= pos && pos <= t.close).map_or("", |t| t.name.as_str()) + } + + /// The source of `from..to` without whitespace and comments between tokens; string and + /// character literals keep their text. + fn src_norm(&self, (from, to): (usize, usize)) -> String { + let mut out = Vec::with_capacity(to - from); + let mut in_literal = false; + for i in from..to { + let (s, m) = (self.src[i], self.m[i]); + if m == b'"' || (m == b'\'' && !in_literal && self.m.get(i + 1) == Some(&b' ')) { + in_literal = !in_literal; + } else if m == b'\'' && in_literal { + in_literal = false; + } + if in_literal || (m == s && !s.is_ascii_whitespace()) { + out.push(s); + } + } + String::from_utf8_lossy(&out).into_owned() + } +} + +/// Every hit in one file, exemptions applied. +pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec<Hit> { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let exec = executed(&m, &tests); + let cfgs = cfg_spans(&m, src.as_bytes()); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs }; + let mut hits: Vec<Hit> = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); + hits.extend(ignore_hits(&file)); + hits.extend(sleep_hits(&file)); + hits.extend(reads_source_hits(&file)); + let allows = allows(src, &file.m); + hits.retain(|h| { + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) + }); + hits.sort(); + hits +} + +/// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from +/// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> { + let mut out = m.to_vec(); + for t in tests { + for at in words(m, b"fn", t.open, t.close).into_iter().chain(words(m, b"macro_rules", t.open, t.close)) { + if let Some((_, _, _, close)) = item_at(m, at).filter(|&(_, _, _, close)| close < t.close) { + blank(&mut out, at, close + 1); + } + } + } + out +} + +/// `(line, rule)` of each exemption comment that names a rule and a reason. +/// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are +/// masked. +fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { + let literals = mask_with(src, false); + let lines = Lines::new(src); + src.match_indices(ALLOW) + .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') + .filter_map(|(p, _)| { + // The reason ends with the line, or with the block comment that holds the marker. + let rest = src[p + ALLOW.len()..].lines().next()?.split("*/").next()?; + let mut words = rest.split_whitespace(); + let rule = Rule::from_id(words.next()?)?; + words.next().map(|_| (lines.of(p), rule)) + }) + .collect() +} + +/// What the rules read of one test. +struct View<'a> { + file: &'a File<'a>, + t: &'a TestFn, + asserts: Vec<MacroCall>, + delegates: bool, + checks: bool, + should_panic: bool, +} + +fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec<Hit> { + let m = &file.exec; + let asserts: Vec<MacroCall> = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); + let none = HashSet::new(); + let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let delegates = calls(m, t.open, t.close) + .iter() + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + let checks = checks_itself(m, t.open, t.close); + let should_panic = should_panic_attr(m, t.attr, t.fn_at); + let v = View { file, t, asserts, delegates, checks, should_panic }; + let mut hits = all_unguarded(&v); + hits.extend(self_compare(&v)); + hits.extend(early_returns(&v)); + hits.extend(env_gates(&v, ctx)); + hits.extend(census(&v, helpers)); + hits.extend(mirrors(&v)); + hits.extend(exact_pixels(&v)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v), echoes(&v), never_run(&v, ctx)].into_iter().flatten()); + hits +} + +/// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, +/// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may +/// not hold, so it does not count. +fn should_panic_attr(m: &[u8], from: usize, to: usize) -> bool { + let attached = words(m, b"should_panic", from, to).into_iter().any(|at| { + let before = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + before && matches!(m.get(skip_ws(m, at + "should_panic".len())), Some(b']' | b'(')) + }); + attached + || words(m, b"cfg_attr", from, to).into_iter().any(|at| { + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = matching(m, open).filter(|&c| m[open] == b'(' && c < to) else { return false }; + let args = split_args(m, open + 1, close); + let name = |&(f, t): &(usize, usize)| { + let a = norm(&m[f..t]); + a == "should_panic" || a.starts_with("should_panic(") + }; + args.first().is_some_and(|&(f, t)| norm(&m[f..t]) == "test") && args.iter().skip(1).any(name) + }) +} + +impl View<'_> { + fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { + self.file.hit(at, rule, &self.t.name, note) + } + + /// A hit for the whole test, on its `fn` line. + fn whole(&self, rule: Rule, note: String) -> Hit { + let mut h = self.hit(self.t.fn_at, rule, note); + h.first = self.file.lines.of(self.t.attr); + h.last = self.file.lines.of(self.t.close); + h + } + + fn body(&self) -> &[u8] { + &self.file.exec[self.t.open..self.t.close] + } + + /// The masked body with assertion failure-message arguments replaced by spaces. + fn body_without_messages(&self) -> Vec<u8> { + let mut body = self.body().to_vec(); + for a in &self.asserts { + for &(from, to) in a.args.iter().skip(guard_arg_count(&a.name)) { + blank(&mut body, from - self.t.open, to - self.t.open); + } + } + body + } + + /// The first argument of an assertion, masked, without whitespace. + fn first_arg(&self, a: &MacroCall) -> String { + a.args.first().map(|&(f, t)| norm(&self.file.m[f..t])).unwrap_or_default() + } +} + +const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; + +/// Calls whose result says how many items a collection has. +const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; + +fn all_unguarded(v: &View) -> Vec<Hit> { + let mut body = v.body_without_messages(); + strip_all_predicates(&mut body); + let locals = bindings(&body); + let checked = v.asserts.iter().any(|a| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let (from, to) = (from - v.t.open, to - v.t.open); + SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) + }) + }); + let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() }; + if checked || first_item_guard(&body, &sizes) { + return vec![]; + } + v.asserts + .iter() + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes)) + .map(|a| { + let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); + h.first = v.file.lines.of(v.t.attr); + h.last = v.file.lines.of(v.t.close); + h + }) + .collect() +} + +/// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`) +/// whose assertions only check presence, non-emptiness or a round trip. +fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> { + let m = &v.file.exec; + // Failure messages run only after an assertion has failed, so a check there does not count. + let unmessaged = v.body_without_messages(); + let helpers_in = |from: usize, to: usize| -> Vec<String> { + calls(&unmessaged, from - v.t.open, to - v.t.open) + .into_iter() + .filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + .map(|(n, _)| n) + .collect() + }; + let weak_in = |from: usize, to: usize, var: &str| { + let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); + let body = &unmessaged[from - v.t.open..to - v.t.open]; + helpers_in(from, to).is_empty() + && !rejects(body) + && !inside.is_empty() + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::<Vec<_>>(), var)) + }; + for at in words(m, b"for", v.t.open, v.t.close) { + let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; + let Some(open) = loop_open(m, kw + 2, v.t.close) else { continue }; + let Some(close) = matching(m, open) else { continue }; + let pattern = String::from_utf8_lossy(&m[at + 3..kw]); + let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); + // A `break` in the body can end the loop before it reaches every entry. + // An asserting helper in the loop source runs for every entry, like one in the body. + if whole_table(&norm(&m[kw + 2..open])) + && helpers_in(kw + 2, open).is_empty() + && words(m, b"break", open, close).is_empty() + && weak_in(open, close, var) + { + return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; + } + } + for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) { + let called = a.args.first().map(|&(f, t)| helpers_in(f, t)).unwrap_or_default(); + if census_condition(&v.first_arg(a), 0, &called) == (true, true) { + return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())]; + } + } + vec![] +} + +/// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and +/// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while +/// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions +/// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting +/// helpers called in the condition) is not a presence check, and a weak right side of an `||` does +/// not count when the left side calls one, since the left side always runs. +fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { + let or = top_level_at(cond, "||").first().copied(); + if depth > 64 || !cond.contains(".all(") { + (false, false) + } else if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + census_condition(&cond[1..cond.len() - 1], depth + 1, helpers) + } else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) { + let side = |s: &str| { + if s.contains(".all(") { + census_condition(s, depth + 1, helpers) + } else { + (weak_predicate(s) && !calls_any(s, helpers) && !rejects(s.as_bytes()), false) + } + }; + let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); + let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; + if or.is_none() { + (l.0 && r.0, l.1 || r.1) + } else if l == (true, true) || r == (true, true) { + (true, true) + } else { + (l.0 || r.0, false) + } + } else { + let table = weak_table_all(cond, helpers); + (table || weak_predicate(cond) && !calls_any(cond, helpers), table) + } +} + +/// Whether `s` calls a function or method named in `names`, with or without a turbofish. +fn calls_any(s: &str, names: &[String]) -> bool { + names.iter().any(|n| { + [format!("{n}("), format!("{n}::<")] + .iter() + .any(|call| s.match_indices(call.as_str()).any(|(at, _)| at == 0 || !is_ident(s.as_bytes()[at - 1]))) + }) +} + +/// Whether a (whitespace-free) `.all(…)` predicate checks only presence. A predicate that calls one +/// of `helpers` is weak only when a presence check can pass without the helper running: a weak left +/// side of an `||`, a weak right side after a left side that calls no helper, or weak operands on +/// both sides of an `&&`. +fn presence_only(pred: &str, helpers: &[String], depth: usize) -> bool { + let body = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); + let (or, and) = (top_level_at(body, "||").first().copied(), top_level_at(body, "&&").first().copied()); + if !calls_any(pred, helpers) { + weak_predicate(pred) + } else if depth > 64 { + false + } else if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + presence_only(&body[1..body.len() - 1], helpers, depth + 1) + } else if let Some(at) = or { + let left = &body[..at]; + presence_only(left, helpers, depth + 1) || !calls_any(left, helpers) && presence_only(&body[at + 2..], helpers, depth + 1) + } else if let Some(at) = and { + presence_only(&body[..at], helpers, depth + 1) && presence_only(&body[at + 2..], helpers, depth + 1) + } else { + false + } +} + +/// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate. +fn weak_table_all(op: &str, helpers: &[String]) -> bool { + let Some(&i) = top_level_at(op, ".all(").last() else { return false }; + let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); + let rest = &op[i + ".all(".len()..]; + let end = arg_end(rest); + // A rejection call checks something only on the branches that run it, like an asserting helper. + let checks: Vec<String> = helpers.iter().cloned().chain(["unwrap_err".into(), "expect_err".into()]).collect(); + rest[end..] == *")" && whole_table(receiver) && !calls_any(&op[..i], helpers) && presence_only(&rest[..end], &checks, 0) +} + +/// Whether `body` calls `.unwrap_err()` or `.expect_err(`, with any whitespace inside the call. +fn rejects(body: &[u8]) -> bool { + let tight: Vec<u8> = body.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(") +} + +/// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. +fn loop_open(m: &[u8], from: usize, to: usize) -> Option<usize> { + let mut i = from; + while i < to { + match m[i] { + b'{' => return Some(i), + b'(' | b'[' => i = matching(m, i)? + 1, + b';' => return None, + _ => i += 1, + } + } + None +} + +/// Calls whose name says they return a whole table. +const TABLE_CALLS: &[&str] = &["all", "catalog", "registry", "presets", "swatches", "entries", "variants", "commands", "builtins", "palette"]; + +/// Whether a (whitespace-free) loop source names a whole table: a `SCREAMING_CASE` constant, an +/// `ALL`, `all()`, `iter()` or `variants()` on a type, or a call named like a catalog. +fn whole_table(src: &str) -> bool { + let src = src.trim_start_matches('&'); + let head: &str = src.split(['.', '(', '[']).next().unwrap_or(""); + let restricted = [ + ".take(", + ".skip(", + ".filter(", + ".filter_map(", + ".take_while(", + ".skip_while(", + ".map_while(", + ".step_by(", + ".nth(", + ".first(", + ".last(", + ".rev().take(", + "[", + ]; + let chain = &src[head.len()..]; + // A `zip` stops at its shorter side and a `flat_map` yields what its closure's iterator yields, + // so a restricted iterator inside either bounds the loop too, as does a range zipped in. + let bounded_inside = [".zip(", ".flat_map("].iter().any(|adapter| { + top_level_at(chain, adapter).into_iter().any(|at| { + let open = at + adapter.len() - 1; + matching(chain.as_bytes(), open).is_none_or(|close| { + let inner = &chain[open + 1..close]; + let range = unparenthesized(inner.trim_end_matches(',')); + restricted.iter().any(|r| inner.contains(r)) + || *adapter == ".zip(" && top_level_at(range, "..").first().is_some_and(|&at| !range[at + 2..].trim_start_matches('=').is_empty()) + }) + }) + }); + if bounded_inside || restricted.iter().any(|r| top_level_contains(chain, r)) { + return false; + } + let last = head.rsplit("::").next().unwrap_or(""); + let screaming = last.len() > 1 + && last.bytes().any(|c| c.is_ascii_uppercase()) + && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + let segments: Vec<&str> = head.split("::").collect(); + let on_type = segments.len() > 1 && segments[segments.len() - 2].starts_with(|c: char| c.is_ascii_uppercase()); + let type_table = on_type && matches!(last, "ALL" | "all" | "iter" | "variants" | "VARIANTS" | "value_variants"); + let named = src[head.len()..].starts_with("()") + && TABLE_CALLS.iter().any(|n| last == *n || last.ends_with(&format!("_{n}")) || last.starts_with(&format!("{n}_"))); + screaming || type_table || named +} + +/// Whether `pat` starts at a position of `s` outside every bracket, so an adapter inside a closure +/// does not count as one on the outer iterator chain. +fn top_level_contains(s: &str, pat: &str) -> bool { + !top_level_at(s, pat).is_empty() +} + +/// The byte offsets where `pat` starts in `s` outside every bracket. +fn top_level_at(s: &str, pat: &str) -> Vec<usize> { + let (s, pat) = (s.as_bytes(), pat.as_bytes()); + let mut depth = 0i32; + let mut found = vec![]; + for (i, c) in s.iter().enumerate() { + if depth == 0 && s[i..].starts_with(pat) { + found.push(i); + } + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + } + found +} + +/// Predicates and comparisons that every entry passes by construction. +const PRESENCE: &[&str] = &[".is_some()", ".is_ok()", ".is_empty()", ".contains(", ".contains_key(", ".len()>0", ".starts_with(", ".is_finite()"]; + +/// Calls on one side of an equality that turn an entry back into itself. +const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from_key", "by_id", "by_name", "lookup", "find"]; + +/// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. +fn weak_predicate(pred: &str) -> bool { + weak_predicate_within(pred, 0) +} + +/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in +/// [`census_condition`]. +fn weak_predicate_within(pred: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } + let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); + if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) { + return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1); + } + if let Some(at) = boolean_split(pred) { + return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); + } + let negated = (pred.len() - pred.trim_start_matches('!').len()) % 2 == 1; + let pred = pred.trim_start_matches('!'); + // A negated check is a presence check only for `!….is_empty()`; `!….is_ok()` checks a rejection. + if negated && !pred.ends_with(".is_empty()") { + return false; + } + if let Some(list) = pred.strip_suffix(".len()>0") { + return !list.contains(['=', '<', '>']); + } + let compares = pred.contains("==") || pred.contains("!=") || pred.contains(['<', '>']) && !pred.contains("::<"); + !compares + && PRESENCE.iter().any(|p| match p.strip_suffix('(') { + Some(call) => pred.rfind(p).is_some_and(|at| matching(pred.as_bytes(), at + call.len()) == Some(pred.len() - 1)), + None => pred.ends_with(p), + }) +} + +/// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares +/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them. +fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { + match guard_arg_count(name) { + 1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))), + 2 if name.ends_with("_ne") => false, + 2 => match args { + [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), + _ => false, + }, + _ => false, + } +} + +/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole +/// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so +/// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's +/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is +/// not a round trip of the entry. +fn round_trip_call(op: &str, var: &str) -> bool { + let mut op = op.trim_start_matches(['&', '*']); + loop { + let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1); + let inner = ["Some(", "Ok(", "("].iter().find(|w| wraps(w)).map(|w| &op[w.len()..op.len() - 1]); + match inner { + Some(inner) => op = inner.trim_start_matches(['&', '*']), + None => break, + } + } + ROUND_TRIP.iter().any(|r| { + op.match_indices(&format!("{r}(")).any(|(at, _)| { + let open = at + r.len(); + !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&']) + && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) + }) + }) +} + +/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not +/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word. +fn reads_ident(s: &str, var: &str) -> bool { + let b = s.as_bytes(); + !var.is_empty() + && s.match_indices(var).any(|(at, _)| { + let end = at + var.len(); + let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); + let path = at > 1 && &b[at - 2..at] == b"::"; + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident) + }) +} + +/// Whether a (whitespace-free) call suffix only unwraps or copies the call's result. +fn only_unwraps(mut rest: &str) -> bool { + const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"]; + loop { + let next = match UNWRAPS.iter().find_map(|s| rest.strip_prefix(s)) { + Some(r) => Some(r), + None if rest.starts_with(".expect(") => matching(rest.as_bytes(), ".expect".len()).map(|close| &rest[close + 1..]), + None => None, + }; + match next { + _ if rest.is_empty() => break true, + Some(r) => rest = r, + None => break false, + } + } +} + +/// Whether an operand is the loop entry itself: `x`, `*x`, `&x`, `Some(x)`, `Ok(x)` or `x.clone()`. +fn is_entry(op: &str, var: &str) -> bool { + let mut op = op.trim_start_matches(['&', '*']); + for wrap in ["Some(", "Ok("] { + if let Some(inner) = op.strip_prefix(wrap).and_then(|r| r.strip_suffix(')')) { + op = inner.trim_start_matches(['&', '*']); + } + } + !var.is_empty() && op.trim_end_matches(".clone()") == var +} + +/// The number of condition or compared operands in a standard assertion macro. +fn guard_arg_count(name: &str) -> usize { + match name { + "assert" | "debug_assert" | "prop_assert" => 1, + "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" | "prop_assert_eq" | "prop_assert_ne" => 2, + _ => 0, + } +} + +/// Blanks `.all(…)` predicates so their checks do not guard the collection. +fn strip_all_predicates(body: &mut [u8]) { + for at in words(body, b"all", 0, body.len()) { + let method = body[..at].trim_ascii_end().ends_with(b"."); + let open = skip_ws(body, at + 3); + let Some(close) = (method && body.get(open) == Some(&b'(')).then(|| matching(body, open)).flatten() else { continue }; + blank(body, at, close + 1); + } +} + +/// Whether test code accesses a first item in a way that fails on an empty collection. +fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { + let compact = norm(body); + let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; + let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); + indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) +} + +/// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. +fn panicking_first_binding(body: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let rest = &body[at + 3..]; + let Some(otherwise) = words(rest, b"else", 0, rest.len()).first().copied() else { return false }; + let binding = norm(&rest[..otherwise]); + let Some(close) = binding.strip_prefix("Some(").and_then(|_| matching(binding.as_bytes(), 4)) else { return false }; + let Some(value) = binding[close + 1..].strip_prefix('=') else { return false }; + let first = value.ends_with(".first()") || value.ends_with(".next()"); + first && !value.contains([';', '{', '}']) && norm(&rest[otherwise + 4..]).starts_with("{panic!(") + }) +} + +/// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would +/// pass by mistake. Left out: a negated result, a closure that says no item matches (whole +/// negations or `!=` comparisons joined only by `&&`), and a collection the test shows cannot be +/// empty ([`least_items`]). +fn unguarded_all(cond: &str, body: &[u8], sizes: &Sizes) -> bool { + all_with_polarity(cond, true, body, sizes) +} + +/// Tracks negation through boolean operands and comparisons with `false`. +fn all_with_polarity(cond: &str, positive: bool, body: &[u8], sizes: &Sizes) -> bool { + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return all_with_polarity(&cond[1..cond.len() - 1], positive, body, sizes); + } + if let Some(at) = boolean_split(cond) { + return all_with_polarity(&cond[..at], positive, body, sizes) || all_with_polarity(&cond[at + 2..], positive, body, sizes); + } + if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { + return all_with_polarity(expr, !positive, body, sizes); + } + if let Some(expr) = cond.strip_prefix('!') { + return all_with_polarity(expr, !positive, body, sizes); + } + positive && positive_all(cond, body, sizes) +} + +/// Finds a boolean operator outside parentheses, brackets and braces. +fn boolean_split(cond: &str) -> Option<usize> { + let b = cond.as_bytes(); + let mut at = 0; + while at < b.len() { + if b[at..].starts_with(b"&&") || b[at..].starts_with(b"||") { + return Some(at); + } + at = if matches!(b[at], b'(' | b'[' | b'{') { matching(b, at)? + 1 } else { at + 1 }; + } + None +} + +fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { + cond.match_indices(".all(").any(|(i, _)| { + let rest = &cond[i + ".all(".len()..]; + let arg = &rest[..arg_end(rest)]; + let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); + let none_match = not_equal_conjunction(body); + let (receiver, need) = receiver_need(&cond[..i], sizes); + !none_match && least_items(receiver, test_body, sizes) < need + }) +} + +/// Whether every boolean operand is a whole negation or `!=` comparison joined only by `&&`. +fn not_equal_conjunction(body: &str) -> bool { + if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + return not_equal_conjunction(&body[1..body.len() - 1]); + } + if let Some(at) = boolean_split(body) { + return body[at..].starts_with("&&") && not_equal_conjunction(&body[..at]) && not_equal_conjunction(&body[at + 2..]); + } + if whole_negation(body) { + return true; + } + let (mut at, mut comparisons) = (0, 0); + let b = body.as_bytes(); + while at < b.len() { + if b[at..].starts_with(b"!=") { + comparisons += 1; + at += 2; + } else if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|') { + return false; + } else if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + at = close + 1; + } else { + at += 1; + } + } + comparisons == 1 +} + +/// Whether `!` negates the whole operand rather than one side of a binary expression. +fn whole_negation(body: &str) -> bool { + let Some(rest) = body.strip_prefix('!') else { return false }; + let rest = rest.trim_start_matches(['!', '*', '&']); + let b = rest.as_bytes(); + let mut at = 0; + while at < b.len() { + if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|' | b'+' | b'-' | b'*' | b'/' | b'%' | b'^') { + return false; + } + at = if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + close + 1 + } else { + at + 1 + }; + } + !rest.is_empty() +} + +/// The fewest items the test shows `receiver` (the text before `.all(`, without its iterator +/// method) to have: a non-empty array literal, a plain local bound to one or to a sized +/// initializer ([`expr_len`]) or filled by a loop ([`loop_fill_len`]), a plain local an earlier +/// equality assertion compares with a non-empty literal, or a field the file declares as an +/// array of a positive length. 0 when the test does not show it. +fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let literal = array_literal_len(receiver, sizes).unwrap_or(0); + let derived = derived_locals(receiver, body).iter().map(|(d, from)| equal_len(d, body, sizes, Some(*from))).max().unwrap_or(0); + literal + .max(bound_len(receiver, body, sizes)) + .max(equal_len(receiver, body, sizes, None)) + .max(derived) + .max(field_len(receiver, sizes)) + .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) +} + +/// Whether `body` has a `let` binding of `name`. +fn binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + body[start..].starts_with(name) && !body.get(start + name.len()).copied().is_some_and(is_ident) + }) +} + +/// Methods that give at least one item for each distinct item they are given, and none from none, +/// with `collect` restricted to known collection targets. +const KEEPING: &[&str] = &["map", "iter", "into_iter", "cloned", "copied", "enumerate", "rev", "collect", "to_vec", "to_owned", "clone"]; + +/// Whether a normalized type names a collection that keeps an item of a non-empty iterator. +fn known_collection(ty: &str) -> bool { + let (name, args) = ty.split_once('<').map_or((ty, None), |(name, args)| (name, args.strip_suffix('>'))); + match name { + "Vec" | "std::vec::Vec" | "String" | "std::string::String" => true, + "Box" | "std::boxed::Box" => args.is_some_and(|args| { + args.starts_with('[') && matching(args.as_bytes(), 0) == Some(args.len() - 1) && !has_top_level(&args.as_bytes()[1..args.len() - 1], b';') + }), + _ => matches!( + name.strip_prefix("std::collections::").unwrap_or(name), + "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "BinaryHeap" | "LinkedList" + ), + } +} + +/// `operand` (masked, whitespace-free) without trailing calls of [`KEEPING`] methods: the +/// collection a compared or bound value was built from. Only the final call may use an +/// inferred `collect` target, when the caller knows it is a collection. +fn keeping_base(operand: &str, inferred_collect: bool) -> &str { + let mut op = operand; + while op.ends_with(')') { + let b = op.as_bytes(); + let mut depth = 0usize; + let Some(open) = (0..b.len()).rev().find(|&i| { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + depth == 0 + }) else { + break; + }; + let mut head = &op[..open]; + let mut target = None; + if head.ends_with('>') { + let Some(turbofish) = head.rfind("::<") else { break }; + target = Some(&head[turbofish + 3..head.len() - 1]); + head = &head[..turbofish]; + } + let Some((rest, method)) = head.rsplit_once('.') else { break }; + if !KEEPING.contains(&method) || (method == "collect" && !target.map_or(inferred_collect && op.len() == operand.len(), known_collection)) { + break; + } + op = rest; + } + op +} + +/// Plain locals of the test bound (`let name = …;`, latest binding) to `receiver` through +/// [`KEEPING`] methods only, so they have no more distinct items than it, when no later code may +/// shrink or replace `receiver` ([`may_shrink`]), paired with the end of each binding. +fn derived_locals(receiver: &str, body: &[u8]) -> Vec<(String, usize)> { + let name = array_receiver(receiver); + if !plain_local(name) { + return vec![]; + } + let mut latest: HashMap<String, (bool, usize)> = HashMap::new(); + for at in words(body, b"let", 0, body.len()) { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + continue; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let (annotation, from) = stmt.split_once('=').unwrap_or(("", "")); + let inferred_collect = annotation.strip_prefix(':').is_some_and(known_collection); + let base = keeping_base(from, inferred_collect); + let derived = base != from && collection_operand(base) == name && !may_shrink(body, name.as_bytes(), stop); + latest.insert(String::from_utf8_lossy(&body[start..end]).into_owned(), (derived, stop)); + } + latest.into_iter().filter(|&(_, (derived, _))| derived).map(|(n, (_, stop))| (n, stop)).collect() +} + +/// The length a `const` or `static` item of the file declares for a plain name +/// (`const NAME: [T; N]`), taking the smallest length across all declarations of that name, +/// or 0 when any declaration has an unknown or non-array type. +fn item_len(receiver: &str, sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let file = sizes.file; + let mut len = None; + for at in words(file, name.as_bytes(), 0, file.len()) { + let before = file[..at].trim_ascii_end(); + let before = before.strip_suffix(b"mut").map_or(before, |b| b.trim_ascii_end()); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + if !keyword(b"const") && !keyword(b"static") { + continue; + } + let colon = skip_ws(file, at + name.len()); + let ty = skip_ws(file, colon + 1); + if file.get(colon) != Some(&b':') || file.get(ty) != Some(&b'[') { + return 0; + } + let Some(close) = matching(file, ty) else { return 0 }; + let count = repeat_count(&file[ty + 1..close], sizes).unwrap_or(0); + len = Some(len.map_or(count, |n: usize| n.min(count))); + } + len.unwrap_or(0) +} + +/// The receiver without its iterator method and the items it needs for `.all(…)` to see one: +/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// than any collection has. +fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { + let r = array_receiver(receiver); + for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { + let Some(at) = r.rfind(method) else { continue }; + let open = at + method.len() - 1; + if matching(r.as_bytes(), open) != Some(r.len() - 1) { + continue; + } + let need = match sizes.count(&r[open + 1..r.len() - 1]) { + Some(k) if k > 0 => { + if exact { + k + } else { + 1 + } + } + _ => usize::MAX, + }; + return (array_receiver(&r[..at]), need); + } + (r, 1) +} + +/// The length of the non-empty literal an earlier equality assertion compares this plain local +/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option<usize>) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return None; + } + let &(lf, lt) = a.args.first()?; + let &(rf, rt) = a.args.get(1)?; + if binding.is_some_and(|from| lf < from || may_change(&body[..lf], name.as_bytes(), from, false)) { + return None; + } + let end = a.args.last().map_or(rt, |&(_, to)| to); + if may_shrink(body, name.as_bytes(), end) { + return None; + } + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + if collection_operand(keeping_base(&left, true)) == name { + Some(literal_len(&right, sizes)) + } else if collection_operand(keeping_base(&right, true)) == name { + Some(literal_len(&left, sizes)) + } else { + None + } + }); + lens.max().unwrap_or(0) +} + +/// Whether `name` is a plain local name: an identifier that does not start with a digit. +fn plain_local(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) +} + +/// Removes one borrow and a slice view from a compared operand. +fn collection_operand(operand: &str) -> &str { + let operand = operand.strip_prefix('&').unwrap_or(operand); + operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) +} + +/// The length of an operand that is wholly an array literal or `vec![…]`, else 0. +fn literal_len(operand: &str, sizes: &Sizes) -> usize { + let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); + if b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) { array_len(&b[1..b.len() - 1], sizes) } else { 0 } +} + +/// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. +fn arg_end(rest: &str) -> usize { + let mut depth = 0i32; + rest.bytes() + .position(|c| { + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + depth < 0 + }) + .unwrap_or(rest.len()) +} + +/// The length of the array literal `receiver` (the text before `.all(`) ends with, through +/// `.iter()` or `.into_iter()`, or `None` when it does not end with one. +fn array_literal_len(receiver: &str, sizes: &Sizes) -> Option<usize> { + let r = array_receiver(receiver); + let b = r.as_bytes(); + if b.last() != Some(&b']') { + return None; + } + let mut depth = 0usize; + for (j, &c) in b.iter().enumerate().rev() { + match c { + b']' => depth += 1, + b'[' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); + return literal.then(|| array_len(&b[j + 1..b.len() - 1], sizes)); + } + } + _ => {} + } + } + None +} + +/// Removes the iterator method from an array receiver. +fn array_receiver(receiver: &str) -> &str { + receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) +} + +/// The fewest items a plain local receiver has after its latest preceding binding still in scope: from the +/// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later +/// statement may shrink or replace it ([`may_shrink`]). +fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let name = name.as_bytes(); + let mut in_scope = words(body, b"let", 0, body.len()).into_iter().rev().filter(|&at| open_at_end(body, at)); + let Some((len, end)) = in_scope.find_map(|at| array_binding(body, at, name, sizes)) else { + return 0; + }; + if may_shrink(body, name, end) { + return 0; + } + len.max(loop_fill_len(body, name, end, sizes)) +} + +/// Whether the block holding offset `at` of `body` is still open at the end of `body`: a binding +/// there is still in scope. +fn open_at_end(body: &[u8], at: usize) -> bool { + let mut depth = 0usize; + for &c in &body[at..] { + match c { + b'{' => depth += 1, + b'}' if depth == 0 => return false, + b'}' => depth -= 1, + _ => {} + } + } + true +} + +/// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type +/// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), +/// and where the statement ends. `None` for a binding of another name. +fn array_binding(body: &[u8], at: usize, name: &[u8], sizes: &Sizes) -> Option<(usize, usize)> { + let mut at = skip_ws(body, at + 3); + if body[at..].starts_with(b"mut") && body.get(at + 3).is_some_and(u8::is_ascii_whitespace) { + at = skip_ws(body, at + 3); + } + let end = at + body[at..].iter().copied().take_while(|&c| is_ident(c)).count(); + if &body[at..end] != name { + return None; + } + let stop = statement_end(body, end); + let stmt = &body[end..stop]; + let eq = (0..stmt.len()).find(|&i| { + stmt[i] == b'=' + && !matches!(stmt.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| stmt[j]), Some(b'=' | b'!' | b'<' | b'>')) + }); + let (annotation, init) = match eq { + Some(eq) => (&stmt[..eq], Some(&stmt[eq + 1..])), + None => (stmt, None), + }; + let annotation = norm(annotation); + if let Some(ty) = annotation.strip_prefix(':') + && ty.starts_with('[') + && matching(ty.as_bytes(), 0) == Some(ty.len() - 1) + { + return Some((repeat_count(&ty.as_bytes()[1..ty.len() - 1], sizes).unwrap_or(0), stop)); + } + Some((init.map_or(0, |init| expr_len(&norm(init), sizes, annotation.strip_prefix(':').unwrap_or(""))), stop)) +} + +/// The index of the `;` that ends the statement starting at `from`, outside brackets, or the +/// end of `body`. +fn statement_end(body: &[u8], from: usize) -> usize { + let mut at = from; + while at < body.len() { + match body[at] { + b';' => return at, + b'(' | b'[' | b'{' => match matching(body, at) { + Some(close) => at = close + 1, + None => return body.len(), + }, + _ => at += 1, + } + } + body.len() +} + +/// The fewest items a (masked, whitespace-free) expression yields: an array literal or `vec![…]`, +/// a literal range, either followed only by methods that keep at least one item of a non-empty +/// input (`map`, `iter`, `into_iter`, `cloned`, `copied`, `enumerate`, `rev`, `chain`, `to_vec`, +/// `to_owned`, `clone`, and `collect` into a known collection or `step_by`, after which at least +/// one is known). Only a final `collect` without a turbofish can use the binding's type. 0 for +/// anything else. +fn expr_len(e: &str, sizes: &Sizes, binding_type: &str) -> usize { + let e = e.strip_prefix("vec!").unwrap_or(e); + let b = e.as_bytes(); + let (mut n, mut rest) = match b.first() { + Some(b'[') => { + let Some(close) = matching(b, 0) else { return 0 }; + (array_len(&b[1..close], sizes), &e[close + 1..]) + } + Some(b'(') => { + let Some(close) = matching(b, 0) else { return 0 }; + (range_len(&e[1..close], sizes), &e[close + 1..]) + } + _ => return range_len(e, sizes), + }; + while !rest.is_empty() { + let Some(tail) = rest.strip_prefix('.') else { return 0 }; + let end = tail.bytes().take_while(|&c| is_ident(c)).count(); + let method = &tail[..end]; + let mut open = end; + if tail[open..].starts_with("::<") { + let mut depth = 0usize; + let Some(close) = tail[open + 2..].bytes().position(|c| { + depth = match c { + b'<' => depth + 1, + b'>' => depth.saturating_sub(1), + _ => depth, + }; + depth == 0 + }) else { + return 0; + }; + open += 2 + close + 1; + } + if tail.as_bytes().get(open) != Some(&b'(') { + return 0; + } + let Some(close) = matching(tail.as_bytes(), open) else { return 0 }; + match method { + "map" | "iter" | "into_iter" | "cloned" | "copied" | "enumerate" | "rev" | "chain" | "to_vec" | "to_owned" | "clone" => {} + "collect" => { + let target = if open > end { + &tail[end + 3..open - 1] + } else if close + 1 == tail.len() { + binding_type + } else { + "" + }; + if !known_collection(target) { + return 0; + } + n = n.min(1); + } + "step_by" => n = n.min(1), + _ => return 0, + } + rest = &tail[close + 1..]; + } + n +} + +/// The number of items in a range of integer literals or constants (`a..b`, `a..=b`); 0 for +/// anything else, an open range included. +fn range_len(e: &str, sizes: &Sizes) -> usize { + let (lo, hi, inclusive) = match e.split_once("..=") { + Some((lo, hi)) => (lo, hi, true), + None => match e.split_once("..") { + Some((lo, hi)) => (lo, hi, false), + None => return 0, + }, + }; + let value = |t: &str| match t.strip_prefix('-') { + Some(t) => sizes.count(t).and_then(|v| i128::try_from(v).ok()).map(|v| -v), + None => sizes.count(t).and_then(|v| i128::try_from(v).ok()), + }; + let (Some(lo), Some(hi)) = (value(lo), value(hi)) else { return 0 }; + let len = hi - lo + i128::from(inclusive); + usize::try_from(len).unwrap_or(0) +} + +/// The number of items in an array literal's masked contents: the count of a repetition, or the +/// elements of a list. +fn array_len(contents: &[u8], sizes: &Sizes) -> usize { + if let Some(count) = repeat_count(contents, sizes) { + return count; + } + if has_top_level(contents, b';') { + return 0; + } + split_args(contents, 0, contents.len()).len() +} + +/// The count of a repetition `[x; N]` (a literal or a `const` of the file), from its masked +/// contents; `None` when they are not a repetition, `Some(0)` when the count is not known. +fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option<usize> { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return Some(sizes.count(&norm(&contents[at + 1..])).unwrap_or(0)), + b'(' | b'[' | b'{' => at = matching(contents, at)? + 1, + _ => at += 1, + } + } + None +} + +/// Whether `c` occurs in `b` outside brackets. +fn has_top_level(b: &[u8], c: u8) -> bool { + let mut at = 0; + while at < b.len() { + match b[at] { + x if x == c => return true, + b'(' | b'[' | b'{' => match matching(b, at) { + Some(close) => at = close + 1, + None => return true, + }, + _ => at += 1, + } + } + false +} + +/// The fewest items a `for` loop after `from`, in the same block, adds to `name`: a loop over a +/// sized source ([`expr_len`]) whose own block (not a nested one) pushes or inserts into `name` +/// on every pass, with no `break`, `continue`, `return` or `?` in the loop. 0 when there is none. +fn loop_fill_len(body: &[u8], name: &[u8], from: usize, sizes: &Sizes) -> usize { + let mut best = 0; + for at in words(body, b"for", from, body.len()) { + if block_depth(&body[from..at]) != Some(0) { + continue; + } + let Some(&in_at) = words(body, b"in", at + 3, body.len()).first() else { continue }; + let Some(open) = (in_at + 2..body.len()).find(|&i| body[i] == b'{' && !has_open_bracket(&body[in_at + 2..i])) else { continue }; + let Some(close) = matching(body, open) else { continue }; + let source = expr_len(&norm(&body[in_at + 2..open]), sizes, ""); + let block = &body[open + 1..close]; + let exits = [&b"break"[..], b"continue", b"return"].iter().any(|w| !words(block, w, 0, block.len()).is_empty()) || contains(block, b"?"); + if source == 0 || exits { + continue; + } + let pushes = words(block, name, 0, block.len()).into_iter().any(|p| { + let before = block[..p].trim_ascii_end(); + let statement = matches!(before.last(), None | Some(b';' | b'{' | b'}')); + let call = norm(&block[p + name.len()..block.len().min(p + name.len() + 16)]); + statement && block_depth(&block[..p]) == Some(0) && [".push(", ".push_back(", ".insert("].iter().any(|m| call.starts_with(m)) + }); + if pushes { + best = best.max(source); + } + } + best +} + +/// The brace depth at the end of `b`, or `None` when it closes a block it did not open. +fn block_depth(b: &[u8]) -> Option<usize> { + let mut depth = 0usize; + for &c in b { + match c { + b'{' => depth += 1, + b'}' => depth = depth.checked_sub(1)?, + _ => {} + } + } + Some(depth) +} + +/// Whether `b` leaves a `(` or `[` open. +fn has_open_bracket(b: &[u8]) -> bool { + let mut depth = 0i32; + for &c in b { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + } + depth > 0 +} + +/// Whether code after `from` may remove items from `name` or replace it. +fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { + may_change(body, name, from, true) +} + +/// Whether code after `from` may change the item count of `name`: an unknown method call, +/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { + const PRESERVING: &[&str] = &[ + "iter", + "iter_mut", + "into_iter", + "len", + "is_empty", + "contains", + "get", + "get_mut", + "first", + "last", + "first_mut", + "last_mut", + "as_slice", + "as_ref", + "clone", + "to_vec", + "to_owned", + "windows", + "chunks", + "chunks_exact", + "sort", + "sort_by", + "sort_by_key", + "sort_unstable", + "sort_unstable_by", + "sort_unstable_by_key", + "reverse", + "binary_search", + "binary_search_by", + "binary_search_by_key", + "starts_with", + "ends_with", + "map", + "concat", + "join", + "keys", + "values", + ]; + const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + words(body, name, from, body.len()).into_iter().any(|p| { + let after = &body[skip_ws(body, p + name.len())..]; + let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); + let before = body[from..p].trim_ascii_end(); + let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); + let called = if after.first() == Some(&b'.') { + let start = skip_ws(after, 1); + let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &after[skip_ws(after, end)..]; + let method = &after[start..end]; + (rest.starts_with(b"(") || rest.starts_with(b"::<")) + && !PRESERVING.iter().any(|m| method == m.as_bytes()) + && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) + } else { + false + }; + assigned || borrowed || called + }) +} + +/// The length of a field the file declares as an array of a positive length (`name: [T; N]`), +/// for a receiver `….name`. 0 when any other `name:` in the file may start a type: anything but +/// an array, a lowercase name that is not a path or a primitive type (a value in a struct +/// expression), or a literal. +fn field_len(receiver: &str, sizes: &Sizes) -> usize { + let Some((owner, field)) = receiver.rsplit_once('.') else { return 0 }; + if owner.is_empty() || !plain_local(field) { + return 0; + } + const PRIMITIVE: &[&str] = &[ + "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", "dyn", "impl", + "fn", "mut", "crate", "self", "super", + ]; + let file = sizes.file; + let mut least: Option<usize> = None; + for at in words(file, field.as_bytes(), 0, file.len()) { + let colon = skip_ws(file, at + field.len()); + if file.get(colon) != Some(&b':') || file.get(colon + 1) == Some(&b':') || at.checked_sub(1).is_some_and(|j| file[j] == b':') { + continue; + } + let ty = skip_ws(file, colon + 1); + let word_end = ty + file[ty..].iter().copied().take_while(|&c| is_ident(c)).count(); + let word = &file[ty..word_end]; + let value = match file.get(ty) { + Some(b'[') => false, + Some(c) if c.is_ascii_digit() || matches!(c, b'"' | b'\'' | b'-') => true, + Some(c) if c.is_ascii_lowercase() || *c == b'_' => { + let path = file[skip_ws(file, word_end)..].starts_with(b"::"); + !path && !PRIMITIVE.iter().any(|p| p.as_bytes() == word) + } + _ => return 0, + }; + if value { + continue; + } + let Some(close) = matching(file, ty) else { return 0 }; + match repeat_count(&file[ty + 1..close], sizes) { + Some(n) if n > 0 => least = Some(least.map_or(n, |l| l.min(n))), + Some(_) => return 0, + None => {} + } + } + least.unwrap_or(0) +} + +/// What the rules know about collection sizes in one masked file: its `const` counts, read on first use. +struct Sizes<'a> { + file: &'a [u8], + consts: OnceCell<HashMap<String, usize>>, +} + +impl Sizes<'_> { + /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the + /// file whose value is one. + fn count(&self, text: &str) -> Option<usize> { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option<usize> { + let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); + let suffix = &text[digits..]; + let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; + if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + return None; + } + text[..digits].replace('_', "").parse().ok() +} + +/// `const NAME: T = <integer literal>;` in a masked file. A name declared more than once with +/// different values, or with a value that is not a literal, is left out (its value is unknown). +fn file_consts(file: &[u8]) -> HashMap<String, usize> { + // `None` for a name declared with a value that is not a literal or with different values. + let mut out: HashMap<String, Option<usize>> = HashMap::new(); + for at in words(file, b"const", 0, file.len()) { + let start = skip_ws(file, at + 5); + let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || skip_ws(file, end) >= file.len() || file[skip_ws(file, end)] != b':' { + continue; + } + let stop = statement_end(file, end); + let stmt = norm(&file[end..stop]); + let Some((_, value)) = stmt.split_once('=') else { continue }; + let value = int_literal(value); + let name = String::from_utf8_lossy(&file[start..end]).into_owned(); + let slot = out.entry(name).or_insert(value); + if *slot != value { + *slot = None; + } + } + out.into_iter().filter_map(|(name, value)| Some((name, value?))).collect() +} + +/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression +/// that checks a size ([`SIZE_CHECKS`]). +struct Binding { + name: Vec<u8>, + end: usize, + counts: bool, + /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). + source: Option<Vec<u8>>, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec<Binding> { + words(body, b"let", 0, body.len()) + .into_iter() + .filter_map(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + return None; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let init = stmt.split_once('=').map_or("", |(_, init)| init); + let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); + let ident = init.bytes().take_while(|&c| is_ident(c)).count(); + let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) + }) + .collect() +} + +/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// point checks a size and was not assigned since, of a collection that no later code may shrink +/// or replace. +fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { + all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { + words(body, &b.name, from, to).into_iter().any(|p| { + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + reaching + .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) + }) + }) +} + +/// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. +fn is_weak(cond: &str) -> bool { + let cond = unparenthesized(cond); + let (negated, expr) = match cond.strip_prefix('!') { + Some(rest) => (true, unparenthesized(rest)), + None => (false, cond), + }; + let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); + let suffix = |s: &str| expr.strip_suffix(s).is_some_and(plain); + if negated { + return suffix(".is_empty()"); + } + suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") +} + +/// `expr` without the balanced parentheses around all of it (`((a.is_ok()))` gives `a.is_ok()`). +fn unparenthesized(mut expr: &str) -> &str { + while expr.starts_with('(') && matching(expr.as_bytes(), 0) == Some(expr.len() - 1) { + expr = &expr[1..expr.len() - 1]; + } + expr +} + +fn only_weak(v: &View) -> Option<Hit> { + let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); + // Failure messages run only after an assertion has failed, so a check there does not count. + let body = v.body_without_messages(); + let other = contains(&body, b"panic!") || rejects(&body); + if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) +} + +/// Methods that return the next value of something each time (`assert_ne!(it.next(), it.next())` +/// compares two items). +const ADVANCING: &[&str] = + &["next", "next_back", "pop", "pop_front", "pop_back", "recv", "try_recv", "read_line", "take", "tick", "step", "advance", "now", "elapsed"]; + +fn self_compare(v: &View) -> Vec<Hit> { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq") || a.name.ends_with("_ne")) + .filter_map(|a| { + let right = *a.args.get(1)?; + let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let calls_with_args = l.replace("()", "").contains(['(', '!']); + let advances = ADVANCING.iter().any(|m| l.contains(&format!(".{m}()"))); + (l == r && !l.is_empty() && !calls_with_args && !advances).then(|| { + let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); + let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); + h.last = v.file.lines.of(end.saturating_sub(1)); + h + }) + }) + .collect() +} + +fn exit_status_only(v: &View) -> Option<Hit> { + let mut body = norm(&v.body_without_messages()).into_bytes(); + let runs = contains(&body, b"Command::new") || contains(&body, b".output()") || contains(&body, b".status()"); + strip_stream_configuration(&mut body); + let reads = + ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); + let status_only = |a: &MacroCall| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let c = norm(&v.file.m[from..to]); + c.contains(".success()") || c.contains(".code()") + }) + }; + if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { + return None; + } + Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) +} + +/// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the +/// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. +fn strip_stream_configuration(body: &mut [u8]) { + for stream in ["stdout", "stderr", "stdin"] { + for at in words(body, stream.as_bytes(), 0, body.len()) { + if body[..at].ends_with(b".") && body[at + stream.len()..].starts_with(b"(") { + blank(body, at, at + stream.len()); + } + } + } +} + +fn no_assertion(v: &View) -> Option<Hit> { + if v.checks || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) +} + +/// Guards that mark a skip for a missing resource or another platform, or a test that runs itself +/// in a child process, matched case-sensitively on the guard without whitespace. +const SKIP_GUARDS: &[&str] = &[ + "in_own_process", + "OWN_PROCESS", + "_TEST_CHILD", + "current_exe()", + "skip_without_craft_fonts", + "CRAFT_FONTS", + "japanese_fonts", + "craft_fonts", + "env::var", + "cfg!(", + "target_os", + "geteuid", + "Command::new", + "File::open", + "fs::read", + "read_dir(", + ".exists()", + "which(", +]; + +/// The same, matched without regard to case. +const SKIP_GUARDS_ANY_CASE: &[&str] = &[ + "installed_family", + "kufi", + "library/fonts", + "default_font(", + "arabic_face", + "arabic_test_face", + "devanagari_test_face", + "joiner_test_faces", + "mark_text(", + "arabic_style", + "has_family", + "variable_font", + "fontdb", + ".face(", + "covers(", + "thai", + "cjk", + "corpus", + "suite_dir", + "json2_file", + "read_fixture", + "samples(", + "pinned(", + "platform()", + "is_mac", + "/system/library", +]; + +fn early_returns(v: &View) -> Vec<Hit> { + let (m, t) = (&v.file.m, v.t); + words(m, b"return", t.open, t.close) + .into_iter() + .filter_map(|at| { + let end = bare_return_end(m, at + "return".len())?; + let rest_empty = m[end..t.close].iter().all(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'}')); + if rest_empty || nested(m, t.open, at) || skip_guard(v.file, t.open, at, end) { + return None; + } + Some(v.hit(at, Rule::EarlyReturn, "returns early on a value from the code under test".into())) + }) + .collect() +} + +/// The end of a bare `return` (`return;`, `return }`, `return Ok(());`) whose keyword ends at `i`. +fn bare_return_end(m: &[u8], i: usize) -> Option<usize> { + let mut j = skip_ws(m, i); + if m[j..].starts_with(b"Ok") { + j += 2; + for c in *b"(())" { + j = skip_ws(m, j); + if m.get(j) != Some(&c) { + return None; + } + j += 1; + } + j = skip_ws(m, j); + } + match m.get(j)? { + b';' => Some(j + 1), + b'}' | b',' => Some(j), + _ => None, + } +} + +/// Whether `pos` is inside a closure or a nested function in the body opened at `open`. +fn nested(m: &[u8], open: usize, pos: usize) -> bool { + let mut stack: Vec<bool> = vec![]; + for i in open..pos { + match m[i] { + b'{' => stack.push(i > open && opens_closure_or_fn(m, open, i)), + b'}' => { + stack.pop(); + } + _ => {} + } + } + stack.contains(&true) +} + +fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { + let from = brace.saturating_sub(160).max(open + 1); + let head = &m[from..brace]; + let start = head.iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let head = String::from_utf8_lossy(&head[start..]).into_owned(); + let head = head.trim_end(); + let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); + let block = head.strip_suffix("move").unwrap_or(head).trim_end(); + let future = block.ends_with("async") && !block[..block.len() - "async".len()].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'); + closure || future || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() +} + +/// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts +/// first; a comment or a printed note from the start of its statement to the end of its line says +/// why it returns; or its guard skips for a resource, a platform or a child process. +fn skip_guard(file: &File, open: usize, at: usize, end: usize) -> bool { + let m = &file.m; + let block = m[open..at].iter().rposition(|&c| c == b'{').map_or(open, |p| p + open); + let stmt = m[open..block].iter().rposition(|&c| c == b';' || c == b'}').map_or(open, |p| p + open); + let line_end = find(m, b"\n", end).unwrap_or(m.len()); + let asserted = macro_calls(m, block, at).iter().any(|c| is_assert_macro(&c.name)); + let printed = macro_calls(m, stmt, at).iter().any(|c| c.name.ends_with("print") || c.name.ends_with("println")); + let commented = (stmt..line_end).any(|i| file.src[i..].starts_with(b"//") && m[i] == b' '); + if asserted || printed || commented { + return true; + } + let guard = norm(&file.src[stmt..end]); + let lower = guard.to_ascii_lowercase(); + let wide = &file.src[stmt.saturating_sub(250).max(open)..end]; + SKIP_GUARDS.iter().any(|g| guard.contains(g)) + || SKIP_GUARDS_ANY_CASE.iter().any(|g| lower.contains(g)) + || (lower.contains("fs::write(") && lower.contains(".is_err()")) + || ["in_own_process", "OWN_PROCESS", "_TEST_CHILD", "current_exe()"].iter().any(|g| contains(wide, g.as_bytes())) + || !words(wide, b"CHILD", 0, wide.len()).is_empty() +} + +fn env_gates(v: &View, ctx: &Ctx) -> Vec<Hit> { + let (m, src, t) = (&v.file.m, v.file.src, v.t); + let mut out = vec![]; + for at in words(m, b"var", t.open, t.close).into_iter().chain(words(m, b"var_os", t.open, t.close)) { + if !m[..at].ends_with(b"env::") { + continue; + } + let Some((name, end)) = env_name(m, src, at) else { continue }; + if ctx.ci_env.contains(&name) || set_by_system(&name) { + continue; + } + if !set_in_file(m, src, &name) { + // The hit sits on `var`; its span reaches the name, which can be on a later line. + let mut hit = v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets")); + hit.last = v.file.lines.of(end); + out.push(hit); + } + } + out +} + +/// Whether the file's code (masked `m`, outside comments and literals) sets `name`: `.env("NAME", …)`, +/// `set_var("NAME", …)`, or a constant `= "NAME";`. The name is read from the source. +fn set_in_file(m: &[u8], src: &[u8], name: &str) -> bool { + let call = |word: &[u8], method: bool| { + words(m, word, 0, m.len()).into_iter().any(|at| { + let dot = m[..at].trim_ascii_end().ends_with(b"."); + (dot || !method) && env_name(m, src, at).is_some_and(|(n, _)| n == name) + }) + }; + let constant = find_all(src, name.as_bytes()).any(|p| { + let (open, close) = (p.wrapping_sub(1), p + name.len()); + let (Some(b'"'), Some(b'"')) = (m.get(open), m.get(close)) else { return false }; + m[..open].trim_ascii_end().ends_with(b"=") && m.get(skip_ws(m, close + 1)) == Some(&b';') + }); + call(b"env", true) || call(b"set_var", false) || constant +} + +/// Every start of `needle` in `hay`. +fn find_all<'a>(hay: &'a [u8], needle: &'a [u8]) -> impl Iterator<Item = usize> + 'a { + let mut from = 0; + std::iter::from_fn(move || { + let at = find(hay, needle, from)?; + from = at + 1; + Some(at) + }) +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`, and the offset of its closing +/// quote. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option<(String, usize)> { + let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); + if m.get(open) != Some(&b'(') { + return None; + } + let quote = skip_ws(m, open + 1); + if m.get(quote) != Some(&b'"') { + return None; + } + let end = string_end(src, quote + 1).saturating_sub(1); + let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| (name.to_owned(), end)) +} + +fn ignore_hits(file: &File) -> Vec<Hit> { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"ignore", 0, m.len()) { + if !m[..at].ends_with(b"#[") { + continue; + } + let j = skip_ws(m, at + "ignore".len()); + let reason = match m.get(j) { + Some(b'=') => { + let q = skip_ws(m, j + 1); + ignore_reason(&file.src[q..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + } + _ => false, + }; + if !reason { + let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); + // The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line. + let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); + hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close)); + out.push(hit); + } + } + out +} + +/// The body of an ordinary or raw string literal used as an ignore reason. +fn ignore_reason(src: &[u8]) -> Option<&[u8]> { + if src.first() == Some(&b'"') { + return src.get(1..string_end(src, 1).saturating_sub(1)); + } + let raw = src.strip_prefix(b"r")?; + let hashes = raw.iter().take_while(|&&c| c == b'#').count(); + if raw.get(hashes) != Some(&b'"') { + return None; + } + let body = hashes + 2; + let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +/// What the file's `use` items bring in for a `thread::spawn` call. +#[derive(Clone, Copy)] +struct Imports { + /// `spawn` names `std::thread::spawn`. + spawn: bool, + /// `thread` names `std::thread`. + thread: bool, +} + +fn sleep_hits(file: &File) -> Vec<Hit> { + let m = &file.m; + // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. + let imported = thread_import(m, "sleep"); + let imports = Imports { spawn: thread_import(m, "spawn"), thread: std_thread_import(m) }; + words(m, b"sleep", 0, m.len()) + .into_iter() + .filter(|&at| { + if !in_regions(&file.regions, at) || m.get(skip_ws(m, at + "sleep".len())) != Some(&b'(') { + return false; + } + let before = m[..at].trim_ascii_end(); + let path = before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end); + let thread_sleep = match path { + Some(p) => p.ends_with(b"thread") && !p.ends_with(b"_thread"), + None => imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + }; + thread_sleep && !polls_or_releases(m, at, imports) + }) + .map(|at| { + let mut hit = file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into()); + // An edit to the loop or spawn around the sleep can remove what exempted it. + if let Some((name, _)) = expression_closure_call(m, at).filter(|&(name, end)| &m[name..end] == b"spawn") { + let end = spawn_statement_end(m, name).unwrap_or(m.len().saturating_sub(1)); + hit.gates.extend(file.lines.of(name)..=file.lines.of(end)); + } else if let Some(WaitBlock { start, open, through_other }) = wait_block(m, at) { + let head_at = start + (m[start..open].len() - m[start..open].trim_ascii_start().len()); + if !through_other || closure_head(m[start..open].trim_ascii()) { + let close = matching(m, open).unwrap_or(m.len().saturating_sub(1)); + // A spawn's span runs through the statement, which holds the use of its handle. + let close = closure_spawn(m, start, open).and_then(|s| spawn_statement_end(m, s)).map_or(close, |end| end.max(close)); + hit.gates.extend(file.lines.of(head_at)..=file.lines.of(close)); + } + } + hit + }) + .collect() +} + +/// Whether a `use` brings in `std::thread::<name>` under its own name, alone or in a `thread::{…}` +/// list. An alias (`thread::spawn as spawn_thread`) brings in another name, and `crate::thread` +/// is not the standard library's module. +fn thread_import(m: &[u8], name: &str) -> bool { + let path = format!("thread::{name}"); + let alias = format!("as{name}"); + words(m, b"use", 0, m.len()).into_iter().any(|u| { + // `norm` drops spaces, so `spawn as s` reads `spawnass`. + let item = norm(&m[u..statement_end(m, u)]); + let named = |i: usize| { + let rest = &item[i + path.len()..]; + let rest = rest.strip_prefix(alias.as_str()).unwrap_or(rest); + !item.as_bytes()[..i].last().copied().is_some_and(is_ident) && !rest.bytes().next().is_some_and(is_ident) + }; + item.match_indices(&path).any(|(i, _)| named(i) && under_std(&item[..i])) + || item.match_indices("thread::{").any(|(i, _)| { + let list = &item[i + "thread::{".len()..]; + let list = &list[..list.find('}').unwrap_or(list.len())]; + under_std(&item[..i]) && !words(list.as_bytes(), name.as_bytes(), 0, list.len()).is_empty() + }) + }) +} + +/// Whether a member of a `use` item whose normalized text before the member is `pre` sits directly +/// under `std`: right after `use std::`, or a top-level member of a `use std::{…}` list. +fn under_std(pre: &str) -> bool { + let pre = pre.strip_prefix("use").unwrap_or(pre); + let pre = pre.strip_prefix("::").unwrap_or(pre); + let Some(rest) = pre.strip_prefix("std::") else { return false }; + rest.is_empty() || (rest.starts_with('{') && rest.ends_with(['{', ',']) && rest.matches('{').count() == 1 + rest.matches('}').count()) +} + +/// Whether a `use` binds the name `thread` to `std::thread`: `use std::thread;`, +/// `use std::{thread, …};` or `use std::thread::{self, …};`. +fn std_thread_import(m: &[u8]) -> bool { + words(m, b"use", 0, m.len()).into_iter().any(|u| { + let item = norm(&m[u..statement_end(m, u)]); + words(item.as_bytes(), b"thread", 0, item.len()).into_iter().any(|i| { + let after = &item[i + "thread".len()..]; + // `{self as worker}` binds another name. + let self_member = + after.strip_prefix("::{").is_some_and(|list| list[..list.find('}').unwrap_or(list.len())].split(',').any(|x| x == "self")); + under_std(&item[..i]) && (after.is_empty() || after.starts_with([';', ',', '}']) || self_member) + }) + }) +} + +/// Calls that pass a value through without reading any state, such as the `unwrap` of +/// `elapsed().checked_sub(D).unwrap()`. +const PASS_THROUGH_CALLS: &[&str] = &["unwrap", "expect", "unwrap_or", "unwrap_or_default", "unwrap_or_else"]; + +/// Macros that print or log their arguments, such as the `println!("{}", t0.elapsed())` of a +/// wait on the clock. +const LOG_MACROS: &[&str] = &["print!", "println!", "eprint!", "eprintln!", "trace!", "debug!", "info!", "warn!", "error!", "log!"]; + +/// Calls that only read or build a time, which a wait on the clock alone makes. +const TIME_CALLS: &[&str] = &[ + "sleep", + "now", + "elapsed", + "duration_since", + "saturating_duration_since", + "checked_sub", + "checked_add", + "from_millis", + "from_secs", + "from_micros", + "from_nanos", + "from_secs_f32", + "from_secs_f64", + "as_secs", + "as_millis", + "as_micros", + "as_nanos", + "as_secs_f32", + "as_secs_f64", + "subsec_millis", + "subsec_micros", + "subsec_nanos", + "mul_f32", + "mul_f64", +]; + +/// The enclosing block's opening brace and the start of the statement that opens it. +fn enclosing_block(m: &[u8], at: usize) -> Option<(usize, usize)> { + let mut depth = 0usize; + let open = (0..at).rev().find(|&j| match m[j] { + b'}' => { + depth += 1; + false + } + b'{' if depth == 0 => true, + b'{' => { + depth -= 1; + false + } + _ => false, + })?; + // The statement that opens the block starts after the last `;`, `{` or `}` outside brackets, so + // a condition such as `json!({}) != 1` stays whole. A block in the condition (`while { … } {`) + // belongs to the statement too. + let mut nest = 0usize; + let mut j = open; + let start = loop { + let Some(k) = j.checked_sub(1) else { break 0 }; + j = k; + match m[j] { + b')' | b']' => nest += 1, + b'}' if nest > 0 => nest += 1, + b'(' | b'[' => nest = nest.saturating_sub(1), + b'{' if nest > 0 => nest -= 1, + b'}' => match opening_brace(m, j).filter(|&o| condition_block(&m[..o])) { + Some(o) => j = o, + None => break j + 1, + }, + b';' if nest == 0 => break j + 1, + b'{' => break j + 1, + _ => {} + } + }; + Some((open, start)) +} + +/// The `{` that the `}` at `close` closes. +fn opening_brace(m: &[u8], close: usize) -> Option<usize> { + let mut depth = 0usize; + (0..close).rev().find(|&j| match m[j] { + b'}' => { + depth += 1; + false + } + b'{' if depth == 0 => true, + b'{' => { + depth -= 1; + false + } + _ => false, + }) +} + +/// Whether a block whose `{` follows `before` is an operand in a condition: it follows `while`, +/// `if`, `match`, `&&`, `||`, `!` or a comparison. +fn condition_block(before: &[u8]) -> bool { + let before = before.trim_ascii_end(); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + // A `!` after a name is a macro's (`m! { … }`), not a negation. + let not = before.strip_suffix(b"!").is_some_and(|b| !b.trim_ascii_end().last().copied().is_some_and(is_ident)); + // `||` after an operand is an `or`; after `(`, `,`, `=`, `move` or `return` it starts a closure. + let or = before.strip_suffix(b"||").map(<[u8]>::trim_ascii_end).is_some_and(|b| { + let ends_word = |w: &[u8]| b.ends_with(w) && !b.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(b[j])); + b.last().copied().is_some_and(|c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'?')) && !ends_word(b"move") && !ends_word(b"return") + }); + // A comparison or shift has a space before `<` or `>` (`0 < { … }`); a generic (`Option<u8> {`), + // `->` and `=>` do not. + let angles = before.iter().rev().take_while(|&&c| c == b'<' || c == b'>').count(); + let compares = (1..=2).contains(&angles) && before.len().checked_sub(angles + 1).is_some_and(|j| before[j].is_ascii_whitespace()); + keyword(b"while") || keyword(b"if") || keyword(b"match") || before.ends_with(b"&&") || or || not || compares || before.ends_with(b"=") +} + +/// `head` without a leading loop label (`'outer:`). +fn strip_label(head: &[u8]) -> &[u8] { + if head.first() == Some(&b'\'') { + let n = 1 + head[1..].iter().take_while(|&&c| is_ident(c)).count(); + if let Some(rest) = head[n..].trim_ascii_start().strip_prefix(b":") { + return rest.trim_ascii_start(); + } + } + head +} + +/// Whether `head` opens the body of a closure without parameters: `|| {`, or `|| -> T {` with a return type. +fn closure_head(head: &[u8]) -> bool { + head.ends_with(b"||") || head.windows(2).rposition(|w| w == b"||").is_some_and(|p| head[p + 2..].trim_ascii_start().starts_with(b"->")) +} + +/// Keywords that cannot be a path segment before `spawn`, such as the `return` of `return ::std::thread::spawn(…);`. +const NOT_PATH: &[&[u8]] = &[ + b"return", b"break", b"yield", b"let", b"else", b"in", b"as", b"move", b"match", b"if", b"while", b"loop", b"for", b"box", b"unsafe", b"async", + b"await", b"const", b"static", b"mut", b"ref", b"dyn", b"impl", +]; + +/// The block that decides whether the sleep at `at` waits: the nearest `while` or `loop`, or the +/// nearest closure without parameters, around it. +struct WaitBlock { + open: usize, + start: usize, + /// The walk passed a block other than an `if`, `else`, `match` or match arm, such as a `let` + /// initializer. Only a closure exempts the sleep then. + through_other: bool, +} + +/// The [`WaitBlock`] around `at`. The walk stops at a function. +fn wait_block(m: &[u8], at: usize) -> Option<WaitBlock> { + let mut at = at; + let mut through_other = false; + loop { + let (open, start) = enclosing_block(m, at)?; + let head = m[start..open].trim_ascii(); + let labeled = strip_label(head); + let keyword = |w: &[u8]| head.starts_with(w) && !head.get(w.len()).copied().is_some_and(is_ident); + let starts_while = labeled.starts_with(b"while") && !labeled.get(5).copied().is_some_and(is_ident); + // A `loop` can be the value of a `let` (`let p = loop { … };`), so it ends the head. + let ends_loop = labeled.ends_with(b"loop") && !labeled.len().checked_sub(5).is_some_and(|j| is_ident(labeled[j])); + if starts_while || ends_loop || closure_head(head) { + return Some(WaitBlock { open, start, through_other }); + } + if !words(head, b"fn", 0, head.len()).is_empty() { + return None; + } + if !head.is_empty() && !keyword(b"if") && !keyword(b"else") && !keyword(b"match") && !head.ends_with(b"=>") { + through_other = true; + } + at = open; + } +} + +/// Whether the `while` loop with head `head` counts its own passes: its condition compares a name +/// with `<`, `<=`, `>`, `>=` or `!=` and nothing else, and its body adds to or subtracts from it. +fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { + let Some(cond) = head.strip_prefix(b"while") else { return false }; + let cond = cond.trim_ascii_start(); + let n = cond.iter().take_while(|&&c| is_ident(c)).count(); + if n == 0 || cond[0].is_ascii_digit() || cond.windows(2).any(|w| w == b"&&" || w == b"||") { + return false; + } + let op = cond[n..].trim_ascii_start(); + let compares = (op.starts_with(b"<") && !op.starts_with(b"<<")) || (op.starts_with(b">") && !op.starts_with(b">>")) || op.starts_with(b"!="); + let name = &cond[..n]; + compares + && words(m, name, open, close).into_iter().any(|w| { + let after = skip_ws(m, w + n); + if matches!(m.get(after..after + 2), Some(b"+=" | b"-=")) { + return true; + } + // `n = n + 1` or `n = n - 1`. + if m.get(after) != Some(&b'=') || m.get(after + 1) == Some(&b'=') { + return false; + } + let value = skip_ws(m, after + 1); + m.get(value..value + n) == Some(name) + && !m.get(value + n).copied().is_some_and(is_ident) + && matches!(m.get(skip_ws(m, value + n)), Some(b'+' | b'-')) + }) +} + +/// Whether the sleep at `at` is the pause of a loop that checks a condition, or the delay of a +/// spawned thread's fallback release. A `while` or `loop` around it polls when its condition or +/// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a +/// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the +/// arguments of `stringify!`, of a [`LOG_MACROS`] macro or of the sleep itself, a nested `fn` name +/// and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose +/// handle is dropped runs beside the test, which does not wait for it. In `while n < bound` with +/// `n += 1`, `n -= 1`, `n = n + 1` or `n = n - 1` in the body, the loop counts its own passes, so +/// only calls in the body count. +fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { + if let Some((name, end)) = expression_closure_call(m, at) { + return &m[name..end] == b"spawn" && dropped_spawn(m, name, imports); + } + let Some(WaitBlock { open, start, through_other }) = wait_block(m, at) else { return false }; + let head = m[start..open].trim_ascii(); + if closure_head(head) { + return closure_spawn(m, start, open).is_some_and(|s| dropped_spawn(m, s, imports)); + } + // A sleep inside another block, such as a `let` initializer, in the loop is reported. + if through_other { + return false; + } + let close = matching(m, open).unwrap_or(m.len()); + let from = if counted_while(m, strip_label(head), open, close) { open } else { start }; + let found = calls_at(m, from, close); + // The arguments of `stringify!`, of a logging macro and of a sleep are not polling work. + let skipped: Vec<(usize, usize)> = found + .iter() + .filter(|(_, name, _)| name == "stringify!" || name == "sleep" || LOG_MACROS.contains(&name.as_str())) + .filter_map(|(p, name, _)| { + let o = skip_ws(m, p + name.len()); + matching(m, o).map(|c| (o, c)) + }) + .collect(); + let before = |p: usize| m[..p].trim_ascii_end(); + // `new` builds a time only as `Duration::new`, with `Duration` as a whole path segment. + let duration_new = |p: usize| { + before(p) + .strip_suffix(b"::") + .map(<[u8]>::trim_ascii_end) + .is_some_and(|q| q.ends_with(b"Duration") && !q.len().checked_sub(9).is_some_and(|j| is_ident(q[j]))) + }; + // A nested `fn` item's name is a declaration, not a call. + let declared = |p: usize| { + let b = before(p); + b.ends_with(b"fn") && !b.len().checked_sub(3).is_some_and(|j| is_ident(b[j])) + }; + found.iter().any(|&(p, ref name, method)| { + !name.ends_with('!') + && !TIME_CALLS.contains(&name.as_str()) + && !PASS_THROUGH_CALLS.contains(&name.as_str()) + && !skipped.iter().any(|&(o, c)| o < p && p < c) + && !(name == "new" && !method && duration_new(p)) + && !(!method && declared(p)) + }) +} + +/// The start of the name of the `spawn(…)` call that takes the closure whose head is `m[start..open]` +/// as its argument directly (`spawn(|| {`, `spawn(move || {`), not through another call such as +/// `spawn(prepare(|| {`. +fn closure_spawn(m: &[u8], start: usize, open: usize) -> Option<usize> { + let head = &m[start..open]; + words(head, b"spawn", 0, head.len()).into_iter().rev().find_map(|s| { + let paren = skip_ws(head, s + "spawn".len()); + if head.get(paren) != Some(&b'(') { + return None; + } + let arg = head[paren + 1..].trim_ascii_start(); + let arg = match arg.strip_prefix(b"move") { + Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(), + _ => arg, + }; + arg.starts_with(b"||").then_some(start + s) + }) +} + +/// The offset of the `;` that ends the statement holding the `spawn(…)` call whose name starts at +/// `at`, so an edit that keeps or joins the handle (`).join().unwrap();`) falls in the hit's span. +fn spawn_statement_end(m: &[u8], at: usize) -> Option<usize> { + let close = matching(m, skip_ws(m, at + "spawn".len()))?; + Some(statement_end(m, close + 1).min(m.len().saturating_sub(1))) +} + +/// For a sleep that is the whole body of a closure without braces (`spawn(|| thread::sleep(D))`), +/// the start and end of the name of the call that takes the closure. +fn expression_closure_call(m: &[u8], at: usize) -> Option<(usize, usize)> { + // The `(` of the call, or the `,` before the argument, that starts the argument holding `at`. + let argument_start = |from: usize, comma: bool| { + let mut depth = 0usize; + let mut j = from; + loop { + j = j.checked_sub(1)?; + match m[j] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth > 0 => depth -= 1, + b'(' if depth == 0 => return Some(j), + b',' if depth == 0 && comma => return Some(j), + b'[' | b'{' | b';' if depth == 0 => return None, + _ => {} + } + } + }; + let stop = argument_start(at, true)?; + let arg = m[stop + 1..at].trim_ascii(); + let arg = match arg.strip_prefix(b"move") { + Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(), + _ => arg, + }; + let params = arg.strip_prefix(b"|")?; + let body = ¶ms[params.iter().position(|&c| c == b'|')? + 1..]; + if !body.iter().all(|&c| is_ident(c) || c == b':' || c.is_ascii_whitespace()) { + return None; + } + let paren = if m[stop] == b'(' { stop } else { argument_start(stop, false)? }; + let end = m[..paren].trim_ascii_end().len(); + let name = m[..end].iter().rposition(|&c| !is_ident(c)).map_or(0, |j| j + 1); + (name < end).then_some((name, end)) +} + +/// Whether the `spawn(…)` call whose name starts at `at` starts a thread and drops its handle. +/// The call is the whole statement: `std::thread::` before it (or `thread::` where a `use` binds +/// `thread` to `std::thread`, or no path where a `use` brings in `std::thread::spawn`) and a `;` after +/// it. A `let`, an assignment, an argument or a chained `.join()` keeps the handle, and a test +/// that joins it waits for the sleep. +fn dropped_spawn(m: &[u8], at: usize, imports: Imports) -> bool { + let from = m[..at].iter().rposition(|&c| !(is_ident(c) || c == b':' || c.is_ascii_whitespace())).map_or(0, |j| j + 1); + if !matches!(m[..from].last().copied(), None | Some(b';' | b'{' | b'}')) { + return false; + } + let path = m[from..at].trim_ascii(); + let path = path.strip_prefix(b"::").map_or(path, <[u8]>::trim_ascii_start); + let mut segments: Vec<&[u8]> = vec![]; + let mut i = 0; + while i < path.len() { + if !is_ident(path[i]) || path[i].is_ascii_digit() { + return false; + } + let segment = i; + while i < path.len() && is_ident(path[i]) { + i += 1; + } + let last = &path[segment..i]; + if NOT_PATH.contains(&last) { + return false; + } + segments.push(last); + i = skip_ws(path, i); + if path.get(i..i + 2) != Some(&b"::"[..]) { + return false; + } + i = skip_ws(path, i + 2); + } + // A `thread::` path names the standard library's module only where a `use` binds it. + let thread = match segments[..] { + [] => imports.spawn, + [b"thread"] => imports.thread, + [b"std", b"thread"] => true, + _ => false, + }; + let paren = skip_ws(m, at + "spawn".len()); + thread && matching(m, paren).is_some_and(|close| m.get(skip_ws(m, close + 1)) == Some(&b';')) +} + +fn reads_source_hits(file: &File) -> Vec<Hit> { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + // The source with comments blanked and literals kept: a path in a comment is not read. + let code = mask_parts(&String::from_utf8_lossy(file.src), true, false); + let mut out = vec![]; + let words_and_notes = [ + (&b"include_str"[..], "includes a .rs file as text"), + (&b"ends_with"[..], "keeps files ending in .rs"), + (&b"read_to_string"[..], "reads a .rs file as text"), + ]; + for (word, note) in words_and_notes { + for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let arg = norm(&code[open + 1..close]); + // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. + let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); + let literal = raw.unwrap_or(&arg); + let rs = match word { + b"ends_with" => literal == "\".rs\"", + // The final path step names the file read: the last literal of `root.join("src/lib.rs")` + // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the + // extension of a final `.with_extension("json")`. A final step whose argument is not a + // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on + // the outer path count: a `.join` inside another step's argument does not. + b"read_to_string" => { + // Grouping around the whole argument hides no step: `(root.join(…))`. + let arg = ungroup(arg.strip_suffix(',').unwrap_or(&arg)); + let step = |s: &'static str| { + rfind_outer(arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + }; + match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { + Some((_, ".with_extension(", ext)) => file_literal(ext) == Some("\"rs\""), + Some((_, _, last)) => file_literal(last).is_some_and(|l| l.ends_with(".rs\"")), + None => file_literal(arg).is_some_and(|l| l.ends_with(".rs\"")), + } + } + _ => arg.trim_end_matches('#').ends_with(".rs\""), + }; + if rs { + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + // The span runs through the argument, so a change to a path on a later line counts. + hit.last = file.lines.of(close); + out.push(hit); + } + } + } + out +} + +/// The offset of the last `pat` in `expr` outside every bracket and string literal. +fn rfind_outer(expr: &str, pat: &str) -> Option<usize> { + let b = expr.as_bytes(); + let (mut depth, mut in_str, mut found) = (0usize, false, None); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + if depth == 0 && b[i..].starts_with(pat.as_bytes()) { + found = Some(i); + } + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + i += 1; + } + found +} + +/// The offset of the `)` that closes the `(` at `open` in `expr`, skipping string literals. +fn outer_close(expr: &str, open: usize) -> Option<usize> { + let b = expr.as_bytes(); + let (mut depth, mut in_str) = (0usize, false); + let mut i = open; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + i += 1; + } + None +} + +/// A whitespace-free expression without the references and parentheses around all of it: +/// `&(root.join("a"))` gives `root.join("a")`. +fn ungroup(mut expr: &str) -> &str { + loop { + let inner = expr.trim_start_matches('&'); + match inner.strip_prefix('(') { + Some(_) if outer_close(inner, 0) == Some(inner.len() - 1) => expr = &inner[1..inner.len() - 1], + _ => return inner, + } + } +} + +/// `s` when it is one complete ordinary string literal (`"a.rs"`, not `"a"+"b"`), or the body of +/// one complete raw string literal in quotes (`r#"a.rs"#` gives `"a.rs"`). +fn whole_literal(s: &str) -> Option<&str> { + if s.starts_with('"') { + return (s.len() > 1 && string_end(s.as_bytes(), 1) == s.len() && s.ends_with('"')).then_some(s); + } + let rest = s.strip_prefix('r')?; + let hashes = rest.len() - rest.trim_start_matches('#').len(); + raw_literal_body(rest).map(|_| &rest[hashes..rest.len() - hashes]) +} + +/// The literal that names the file of a whitespace-free path expression, quotes included: one +/// complete string literal, the file literal of a `format!`-family or `concat!` call +/// ([`last_literal`]), or the same inside `Path::new(…)` or `PathBuf::from(…)`. `None` for any +/// other expression: `"data.json".trim_end_matches(".rs")` names `data.json`, not its last literal. +fn file_literal(expr: &str) -> Option<&str> { + let e = ungroup(expr.strip_suffix(',').unwrap_or(expr)); + if let Some(l) = whole_literal(e) { + return Some(l); + } + let open = e.find('(')?; + if outer_close(e, open) != Some(e.len() - 1) { + return None; + } + let head = e[..open].trim_start_matches("std::").trim_start_matches("path::"); + match head { + "format!" | "format_args!" | "concat!" => last_literal(e), + "Path::new" | "PathBuf::from" => file_literal(&e[open + 1..e.len() - 1]), + _ => None, + } +} + +/// The last string literal in a (whitespace-free) expression, quotes included. Inside a +/// `format!`-family call, an argument is not the file name, so the format string is returned +/// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. +fn last_literal(arg: &str) -> Option<&str> { + let close = arg.rfind('"')?; + let open = arg[..close].rfind('"')?; + let b = arg.as_bytes(); + let mut depth = 0usize; + for i in (0..open).rev() { + match b[i] { + b')' => depth += 1, + b'(' if depth > 0 => depth -= 1, + b'(' => { + let head = arg[..i].strip_suffix('!').unwrap_or(""); + let name = head.rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).next().unwrap_or(""); + if matches!(name, "format" | "format_args") { + let first = arg[i + 1..].strip_prefix('"')?; + let end = first.find('"')?; + return Some(&arg[i + 1..i + 2 + end + 1]); + } + } + _ => {} + } + } + Some(&arg[open..=close]) +} + +// ---- Mirrors, echoes, never-run tests and exact pixels ---- + +/// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. +const MIRROR_NEUTRAL: &[&str] = &[ + "new", + "from", + "into", + "default", + "clone", + "to_string", + "to_owned", + "to_vec", + "iter", + "into_iter", + "collect", + "unwrap", + "expect", + "len", + "get", + "as_str", + "as_ref", + "as_slice", + "format", + "vec", + "Some", + "Ok", + "Err", + "Box", + "String", + "Vec", + "map", + "cloned", + "copied", +]; + +/// The function a whitespace-free operand starts by calling, with its path: `f` in `f(x).g()`, +/// `Kind::parse` in `Kind::parse(s)`. A method call on a value (`doc.node(id)`) is not one: two reads of the same +/// accessor compare two different things. +fn head_call(op: &str) -> Option<&str> { + let b = op.as_bytes(); + let mut i = 0; + loop { + let end = i + b.get(i..)?.iter().take_while(|&&c| is_ident(c)).count(); + if end == i || b[i].is_ascii_digit() { + return None; + } + match b.get(end) { + Some(b':') if b.get(end + 1) == Some(&b':') => i = end + 2, + Some(b'(') => return Some(&op[..end]), + _ => return None, + } + } +} + +/// The offset of the first top-level `+`, `-`, `*` or `/` in a whitespace-free operand. +fn first_arithmetic(op: &str) -> Option<usize> { + ["+", "-", "*", "/"].iter().flat_map(|o| top_level_at(op, o)).min() +} + +/// The whitespace-free source text of the arguments of the call an operand starts with, read from +/// `code` (the source with comments blanked and string literals kept), so a comment beside a key +/// is not part of it. +fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option<Vec<String>> { + let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; + let close = matching(&f.m, open)?; + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) +} + +/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys. +fn norm_outside_literals(b: &[u8]) -> String { + let mut out = Vec::with_capacity(b.len()); + let mut in_str = false; + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + out.push(c); + if c == b'\\' { + if let Some(&n) = b.get(i + 1) { + out.push(n); + i += 1; + } + } else if c == b'"' { + in_str = false; + } + } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { + in_str = true; + out.push(c); + } else if c == b'r' && !(i > 0 && is_ident(b[i - 1])) && matches!(b[i + 1..].iter().find(|&&h| h != b'#'), Some(b'"')) { + // A raw literal runs to its own closing delimiter: the `"` in `r#"A" B"#` does not end it. + let mut sink = vec![]; + let end = after_ident(b, &mut sink, i, false); + out.extend_from_slice(&b[i..end]); + i = end; + continue; + } else if !c.is_ascii_whitespace() { + out.push(c); + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`, +/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal. +fn raw_literal_body(s: &str) -> Option<&str> { + let hashes = s.len() - s.trim_start_matches('#').len(); + let close = format!("\"{}", "#".repeat(hashes)); + let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?; + (!body.contains(close.as_str())).then_some(body) +} + +/// An argument that names an entry rather than a quantity: a string or integer literal, or a local, +/// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). +fn key_like(arg: &str) -> bool { + let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); + match arg.as_bytes().first() { + Some(b'"') => whole_literal(arg).is_some(), + Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), + Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), + Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), + None => false, + } +} + +/// `assert_eq!(f(a), f(b) <op> …)`: the expected side derives its value from a second call of the +/// same function with arithmetic, so a fault in `f` can move both sides together. Identical sides +/// are `self-compare`'s. Left out: the same arithmetic on both sides (`f(a) * v == f(b) * v` +/// checks that two inputs agree, as a periodicity check does), and two reads at different entries +/// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. +fn mirrors(v: &View) -> Vec<Hit> { + let code = std::cell::OnceCell::new(); + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq")) + .filter_map(|a| { + let (lr, rr) = (*a.args.first()?, *a.args.get(1)?); + let (l, r) = (norm(&v.file.m[lr.0..lr.1]), norm(&v.file.m[rr.0..rr.1])); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let name = head_call(l)?; + // Two calls compared as they are check that two inputs agree, which is a real check. + // Arithmetic on exactly one side, in either order, derives that side from the other call. + let derived = match (first_arithmetic(l), first_arithmetic(r)) { + (None, None) => false, + (Some(i), Some(j)) => l[i..] != r[j..], + _ => true, + }; + let last = name.rsplit("::").next().unwrap_or(name); + if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { + return None; + } + let code: &Vec<u8> = code.get_or_init(|| mask_parts(&String::from_utf8_lossy(v.file.src), true, false)); + let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); + let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); + let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); + (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + }) + .collect() +} + +/// Methods that only read a value the test built itself. +const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"]; + +/// Lowercase names that are types or keywords, not locals. +const PLAIN_NAMES: &[&str] = &[ + "true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "char", + "str", +]; + +fn screaming_or_camel(name: &str) -> bool { + name.as_bytes().first().is_some_and(u8::is_ascii_uppercase) +} + +/// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the +/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)` +/// when it reads none, `None` when it calls or reads anything else. +fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> { + let b = op.as_bytes(); + let mut reads_local = false; + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) { + // Number suffixes (`1.0f32`, `2_u8`) are part of the literal. + if b[i].is_ascii_digit() { + i += b[i..].iter().take_while(|&&c| is_ident(c)).count(); + continue; + } + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let name = &op[i..end]; + let after = &op[end..]; + let method = op[..i].ends_with('.') && !op[..i].ends_with(".."); + let path_tail = op[..i].ends_with("::"); + if method { + if after.starts_with('(') && !FIXTURE_READS.contains(&name) { + return None; + } + } else if after.starts_with("::") || PLAIN_NAMES.contains(&name) { + } else if after.starts_with('!') && !after.starts_with("!=") { + // `format!` can read locals inside its string (`"{got:?}"`), which masking hides. + if name != "vec" { + return None; + } + } else if after.starts_with('(') { + let builder = ["Some", "Ok", "Err"].contains(&name) + || (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p))) + || (!path_tail && screaming_or_camel(name)); + if !builder { + return None; + } + } else if after.starts_with(':') || screaming_or_camel(name) { + // A field name in a struct literal, a constant or a variant. + } else if path_tail { + return None; + } else { + match local(name) { + Some(true) => reads_local = true, + _ => return None, + } + } + i = end; + } + Some(reads_local) +} + +/// The initializer of the last immutable `let <name> = …;` in `body[..before]`: `None` when there is +/// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The +/// initializer comes with the offset of its `let`, where the names it reads are resolved. +fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(String, usize)>> { + let found = let_init(body, name, before); + // A `for` pattern binds its names inside the loop body only, to values the loop produces. + let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { + // `in` is found as a word outside the pattern's brackets, so a line break around it still + // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. + let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; + let Some((open, close)) = block_after(body, kw + 2) else { return false }; + // Words stay apart, so `mut n` binds `n`. + let pattern = norm_words(&body[at + 3..kw]); + open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() + }); + // A match arm's pattern binds its names inside that arm only, and a closure's parameters + // inside its body only. + let inner = loop_at.max(arm_binding(body, name, before)).max(closure_binding(body, name, before)); + match (inner, &found) { + (Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init), + (Some(_), _) => Some(None), + (None, _) => found.map(|(init, _)| init), + } +} + +/// The offset of the parameter list of the innermost closure whose parameters bind `name` and whose +/// body holds `before`: `for_each(|n| assert_eq!(n, 1))` binds `n`. +fn closure_binding(body: &[u8], name: &str, before: usize) -> Option<usize> { + let mut found = None; + let mut i = 0; + while i < before.min(body.len()) { + if body[i] != b'|' { + i += 1; + continue; + } + // A closure's `|` follows an opening bracket, a separator, `=` or `move`; `a | b` and + // `a || b` follow an operand. + let lead = body[..i].trim_ascii_end(); + let opens = lead.last().is_none_or(|&c| matches!(c, b'(' | b'[' | b'{' | b',' | b'=' | b';')) || lead.ends_with(b"move"); + let Some(close) = body[i + 1..].iter().position(|&c| c == b'|').map(|p| p + i + 1) else { break }; + if !opens || close == i + 1 { + i = if opens { close + 1 } else { i + 1 }; + continue; + } + let params = &body[i + 1..close]; + let from = skip_ws(body, close + 1); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&k| match body[k] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' | b';' => depth == 0, + _ => false, + }) + } + }; + if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { + found = Some(i); + } + i = close + 1; + } + found +} + +/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body +/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> { + let mut found = None; + for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm. + let mut depth = 0usize; + let mut start = arrow; + while start > 0 { + match body[start - 1] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => break, + b'(' | b'[' | b'{' => depth -= 1, + b',' if depth == 0 => break, + _ => {} + } + start -= 1; + } + // A guard (`Some(x) if x == n`) reads names; it does not bind them. + let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + let pattern = norm_words(&body[start..guard]); + if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + continue; + } + // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. + let from = skip_ws(body, arrow + 2); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&i| match body[i] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' => depth == 0, + _ => false, + }) + } + }; + if end.is_some_and(|end| before < end) { + found = Some(arrow); + } + } + found +} + +/// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. +fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { + let mut found = None; + for at in words(body, b"let", 0, before) { + let start = skip_ws(body, at + 3); + let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); + let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; + let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let head = body[..at].trim_ascii_end(); + let keyword = + [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if keyword.is_some() { + // `if let` and `while let` bind the pattern's names inside their body only. + if let Some((eq, open, close)) = let_body(body, n0) { + let pattern = norm_words(&body[n0..eq]); + if open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + found = Some((None, at)); + } + } + continue; + } + let stop = statement_end(body, n1); + if stop > before || block_close(body, at) < before { + continue; + } + let rest = norm(&body[n1..stop]); + let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); + if plain && &body[n0..n1] == name.as_bytes() { + let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); + found = Some((if is_mut { None } else { init }, at)); + } else if !plain { + // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). + let pattern = norm_words(&body[n0..stop]); + let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + found = Some((None, at)); + } + } + } + found +} + +/// The `=` that ends the pattern of an `if let` or `while let` starting at `from`, and the braces of +/// its body after the scrutinee ([`block_after`]). The `=` sits outside every bracket, so the braces +/// of a struct pattern (`if let Row { n } = …`) are part of the pattern, and it is not part of `==`, +/// `=>`, `..=`, `<=`, `>=` or `!=`. +fn let_body(body: &[u8], from: usize) -> Option<(usize, usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => return None, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return None, + b'=' if depth == 0 + && !matches!(body.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| body[j]), Some(b'=' | b'.' | b'<' | b'>' | b'!')) => + { + return block_after(body, i + 1).map(|(open, close)| (i, open, close)); + } + _ => {} + } + } + None +} + +/// The depth of the brackets left open at the end of `b`. +fn bracket_depth(b: &[u8]) -> isize { + b.iter() + .map(|&c| match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }) + .sum() +} + +/// The braces of the block that follows an expression starting at `from`: the first `{` outside +/// parentheses and brackets, and its match. +fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth = depth.saturating_sub(1), + b'{' if depth == 0 => return matching(body, i).map(|close| (i, close)), + b';' | b'}' if depth == 0 => return None, + _ => {} + } + } + None +} + +/// Where the innermost block holding `at` closes: its `}`, or the end of `body`. +fn block_close(body: &[u8], at: usize) -> usize { + let mut depth = 0usize; + for i in (0..at).rev() { + match body[i] { + b'}' => depth += 1, + b'{' if depth == 0 => return matching(body, i).unwrap_or(body.len()), + b'{' => depth -= 1, + _ => {} + } + } + body.len() +} + +/// `inert` for an operand of the test at `pos`, resolving locals through their initializers. +fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option<bool> { + let local = |name: &str| -> Option<bool> { + if depth > 8 { + return None; + } + let (init, at) = reaching_init(body, name, pos)??; + inert_at(body, &init, at, depth + 1).map(|_| true) + }; + inert(op, &local) +} + +/// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and +/// literals, or the test's own locals bound to them, so no result of the code under test is checked. +fn echoes(v: &View) -> Option<Hit> { + if v.asserts.is_empty() || v.delegates || v.should_panic { + return None; + } + let body = v.body_without_messages(); + if contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err(") { + return None; + } + let mut reads_local = false; + for a in &v.asserts { + let n = guard_arg_count(&a.name); + if n == 0 { + return None; + } + for &(from, to) in a.args.iter().take(n) { + let op = norm(&body[from - v.t.open..to - v.t.open]); + reads_local |= inert_at(&body, &op, from - v.t.open, 0)?; + } + } + Some(if reads_local { + v.whole(Rule::FixtureOnly, "every assertion reads only locals the test bound to literals or constants".into()) + } else { + v.whole(Rule::ConstantEcho, "every assertion compares only constants and literals".into()) + }) +} + +/// A target CI builds and runs the tests on. +struct Target { + os: &'static str, + family: &'static str, + arch: &'static str, +} + +/// The shared gate (Linux) and the FreeBSD workflow run every test. +const CI_TARGETS: &[Target] = &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }]; + +/// The printing workflow also runs the app's tests and the UI crate's print tests on Windows. +const WINDOWS_TARGET: Target = Target { os: "windows", family: "windows", arch: "x86_64" }; + +/// Desktop targets that CI does not test on, by name. A test that builds on one of them tests code +/// or behavior of that platform. +const PLATFORM_TARGETS: &[(&str, Target)] = &[ + ("macOS", Target { os: "macos", family: "unix", arch: "aarch64" }), + ("macOS", Target { os: "macos", family: "unix", arch: "x86_64" }), + ("Windows", Target { os: "windows", family: "windows", arch: "x86_64" }), + ("Windows", Target { os: "windows", family: "windows", arch: "aarch64" }), +]; + +fn windows_runs(path: &str) -> bool { + path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" +} + +/// The value of the contents of an ordinary Rust string literal: `\x`, `\u{…}` and the single-character +/// escapes decoded. An escape it cannot read is kept as written. +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('0') => out.push('\0'), + Some(c @ ('\\' | '"' | '\'')) => out.push(c), + Some('x') => { + let hex: String = chars.by_ref().take(2).collect(); + match u8::from_str_radix(&hex, 16) { + Ok(v) if v < 0x80 => out.push(char::from(v)), + _ => out.push_str(&format!("\\x{hex}")), + } + } + Some('u') if chars.peek() == Some(&'{') => { + let body: String = chars.by_ref().take_while(|&c| c != '}').collect(); + match u32::from_str_radix(&body[1..].replace('_', ""), 16).ok().and_then(char::from_u32) { + Some(v) => out.push(v), + None => out.push_str(&format!("\\u{body}}}")), + } + } + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + +/// The offsets of the commas in an attribute's argument list `s` that separate its arguments: +/// outside brackets and outside string literals, so `target_os = "("` and `path = "a,b.rs"` stay +/// whole. +fn attr_commas(s: &str) -> Vec<usize> { + let b = s.as_bytes(); + let (mut depth, mut i, mut out) = (0i32, 0, vec![]); + while i < b.len() { + match b[i] { + b'"' => { + // A raw string (`r#"…"#`) ends at a quote followed by as many `#` as it opened with, + // and has no escapes. + let hashes = b[..i].iter().rev().take_while(|&&c| c == b'#').count(); + let raw = b[..i - hashes].last() == Some(&b'r'); + let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', if raw { hashes } else { 0 })).collect(); + i += 1; + while i < b.len() && !b[i..].starts_with(&close) { + i += if !raw && b[i] == b'\\' { 2 } else { 1 }; + } + i += close.len(); + continue; + } + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b',' if depth == 0 => out.push(i), + _ => {} + } + i += 1; + } + out +} + +/// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something +/// else (a feature, `debug_assertions`, an unknown key). +fn cfg_value(p: &str, t: &Target) -> Option<bool> { + for (head, all) in [("all(", true), ("any(", false)] { + if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { + let mut parts = vec![]; + let mut start = 0; + for at in attr_commas(args).into_iter().chain([args.len()]) { + if at > start { + parts.push(cfg_value(&args[start..at], t)); + } + start = at + 1; + } + return if parts.contains(&Some(!all)) { + Some(!all) + } else if parts.iter().all(Option::is_some) { + Some(all) + } else { + None + }; + } + } + if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + let arg = arg.trim(); + let arg = arg.strip_suffix(',').unwrap_or(arg).trim_end(); + return cfg_value(arg, t).map(|v| !v); + } + // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. + // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's + // contents are kept as written. + let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { + Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()), + None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), + }); + let value = value.as_str(); + match key { + "test" => Some(true), + "unix" => Some(t.family == "unix"), + "windows" => Some(t.family == "windows"), + "target_os" => Some(t.os == value), + "target_family" => Some(t.family == value), + "target_arch" => Some(t.arch == value), + "target_pointer_width" => Some(value == "64"), + _ => None, + } +} + +/// A `cfg` attribute found by [`cfg_attrs`]. +struct CfgAttr { + pred: String, + /// The offset of the attribute's `cfg` or `cfg_attr`. + at: usize, + /// The offset of its closing `]`. + end: usize, + inner: bool, +} + +/// The `#[cfg(…)]`, `#![cfg(…)]` and `#[cfg_attr(<condition>, cfg(…))]` attributes in `m[from..to]`, +/// sorted by offset. A nested `cfg` becomes `any(not(<condition>),<predicate>)`: it removes the item +/// only when the condition holds. `m` is the masked text of `src`. +fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<CfgAttr> { + let mut out = vec![]; + for (word, nested) in [(&b"cfg"[..], false), (&b"cfg_attr"[..], true)] { + for at in words(m, word, from, to) { + let before = m[..at].trim_ascii_end(); + let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue }; + let inner = hash.ends_with(b"#!"); + if !inner && !hash.ends_with(b"#") { + continue; + } + let open = skip_ws(m, at + word.len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + continue; + } + let text = pred_text(&src[open + 1..close]); + if !nested { + out.push(CfgAttr { pred: text, at, end, inner }); + continue; + } + for pred in cfg_attr_preds(&text, None) { + out.push(CfgAttr { pred, at, end, inner }); + } + } + } + out.sort_by_key(|a| a.at); + out +} + +/// The `cfg` predicates inside the arguments of a `cfg_attr(<condition>, …)`, each made +/// `any(not(<conditions>),<predicate>)`. A nested `cfg_attr` adds its condition to the enclosing +/// ones: `cfg_attr(unix, cfg_attr(test, cfg(p)))` gives `any(not(all(unix,test)),p)`. +fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec<String> { + let cuts = attr_commas(text); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(p) = arg.strip_prefix("cfg(").and_then(|p| p.strip_suffix(')')) { + out.push(format!("any(not({cond}),{p})")); + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + out.extend(cfg_attr_preds(n, Some(&cond))); + } + start = cut + 1; + } + out +} + +/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the +/// string literals `target_os = "macos"` needs, so only comments are blanked. +fn pred_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The predicates of the `cfg` attributes of [`cfg_spans`] whose item holds `pos`, each with the +/// offsets where its attribute starts and ends. +fn cfgs_at(spans: &[CfgSpan], pos: usize) -> Vec<(String, usize, usize)> { + spans.iter().filter(|s| s.span.0 <= pos && pos <= s.span.1).map(|s| (s.pred.clone(), s.at, s.end)).collect() +} + +/// A `cfg` attribute and the item it covers, from its start to its closing brace. +struct CfgSpan { + pred: String, + at: usize, + end: usize, + span: (usize, usize), +} + +/// Every `cfg` attribute in `src` ([`cfg_attrs`]) with the item it covers, read once per file and +/// queried for each test or declaration with [`cfgs_at`]. +fn cfg_spans(m: &[u8], src: &[u8]) -> Vec<CfgSpan> { + let mut out = vec![]; + for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { + let span = if inner { + // An inner attribute covers the file (or the module) it opens. + let enclosing = m[..at].iter().rposition(|&c| c == b'{'); + enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) + } else { + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole, as `fn_after` does. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + match (m[open], matching(m, open)) { + (b'{', Some(close)) => (at, close), + _ => continue, + } + }; + out.push(CfgSpan { pred, at, end, span }); + } + out +} + +/// Whether the files directly in `dir` are crate target roots: `tests`, `benches` or `examples` +/// beside a crate's `src`, or `src/bin`. +fn is_root_dir(dir: &str) -> bool { + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin") +} + +/// Whether the modules the file `path` declares by name sit in its own directory: `mod.rs`, +/// `lib.rs`, `main.rs` and every crate root (`tests/smoke.rs`, `build.rs`). +fn owns_its_dir(path: &str) -> bool { + let file = path.rsplit_once('/').map_or(path, |(_, f)| f); + ["mod.rs", "lib.rs", "main.rs"].contains(&file) || module_parent(path).is_none() +} + +/// Whether `path` is a `mod.rs` one directory below a target directory (`tests/common/mod.rs`). +fn beside_roots(path: &str) -> bool { + path.rsplit_once('/').is_some_and(|(dir, file)| file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up))) +} + +/// The routes to each [`beside_roots`] file of `files`: every target root in the directory above it +/// (`tests/smoke.rs` for `tests/common/mod.rs`) may load it with `mod common;`. +fn root_routes(files: &[String]) -> Overrides { + let mut out: Overrides = HashMap::new(); + for child in files.iter().filter(|p| beside_roots(p)) { + let Some((up, _)) = child.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')) else { continue }; + let roots = files.iter().filter(|p| p.rsplit_once('/').is_some_and(|(d, f)| d == up && f.ends_with(".rs"))); + out.entry(child.clone()).or_default().extend(roots.map(|r| (r.clone(), vec![]))); + } + out +} + +/// `overrides` with the routes of [`root_routes`] added. +fn with_root_routes(mut overrides: Overrides, files: &[String]) -> Overrides { + for (child, routes) in root_routes(files) { + let known = overrides.entry(child).or_default(); + for route in routes { + if !known.contains(&route) { + known.push(route); + } + } + } + overrides +} + +/// The module name a file declares and the files that may declare it with `mod <name>;`, or `None` +/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or +/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `src` holds modules, not test targets. A `mod.rs` one directory below a target directory +/// (`tests/common/mod.rs`) has no candidates here: the target roots beside that directory load it +/// (`tests/smoke.rs` with `mod common;`), and [`root_routes`] lists them. +fn module_parent(path: &str) -> Option<(&str, Vec<String>)> { + let (dir, file) = path.rsplit_once('/')?; + if beside_roots(path) { + return Some((dir.rsplit_once('/')?.1, vec![])); + } + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (is_root_dir(dir) && file != "mod.rs") { + return None; + } + let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; + let mut candidates: Vec<String> = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); + candidates.push(format!("{parent}.rs")); + Some((name, candidates)) +} + +/// Where a module file is loaded from: the file `path`, the name `name` it declares by default and +/// the inline modules `chain` (outermost first) its declaration must sit in. +struct Loaded<'a> { + path: &'a str, + name: &'a str, + chain: &'a [String], +} + +/// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the +/// `mod <name>;` declarations that load it (by name, or through a `#[path]` override) and on the +/// items, inline modules and file around them, with the 1-based lines of those declarations and +/// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` +/// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which +/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only +/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`). +fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec<String>, Vec<usize>)> { + let m = mask(src); + let lines = Lines::new(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = owns_dir || owns_its_dir(parent); + let mut default_dir = if mod_rs { dir.to_owned() } else { join_path(dir, file.strip_suffix(".rs").unwrap_or(file)) }; + for seg in want.chain { + default_dir = join_path(&default_dir, seg); + } + let (mut each, mut at_lines) = (vec![], vec![]); + // The file's `cfg` attributes, read on the first declaration that loads `want`. + let mut spans: Option<Vec<CfgSpan>> = None; + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + // The conditions under which the inline modules around the declaration resolve to `want.chain`. + let mut via_chain: Vec<Vec<String>> = + inline_routes(&m, src.as_bytes(), at).into_iter().filter(|(c, _)| c == want.chain).map(|(_, k)| k).collect(); + let inline_cond = match via_chain.len() { + 0 => continue, + 1 => via_chain.pop().filter(|k| !k.is_empty()).map(|k| format!("all({})", k.join(","))), + _ => Some(format!("any({})", via_chain.iter().map(|k| format!("all({})", k.join(","))).collect::<Vec<_>>().join(","))), + }; + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + // A `cfg_attr` override loads its path where its condition holds, and the default (or a + // plain `#[path]`) elsewhere. + let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); + let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; + let fallback = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => via != Via::Named && overrides_here(&rel), + None => { + via != Via::Path + && &m[start..end] == want.name.as_bytes() + && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) + } + }; + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let route = match (fallback, selected.is_empty(), conditional.is_empty()) { + (true, _, true) => None, + (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))), + (true, false, false) => { + let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + (!others.is_empty()).then(|| format!("not(any({}))", others.join(","))) + } + (false, true, _) => continue, + (false, false, _) => Some(format!("any({})", selected.join(","))), + }; + // Inner attributes cover the file, and [`cfgs_at`] reads them. + let attrs: Vec<CfgAttr> = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); + at_lines.push(lines.of(at)); + // Every line of a multiline attribute counts: an edit inside its predicate changes it. + at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); + let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect(); + if let Some(route) = route { + preds.push(route); + at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at)); + } + preds.extend(inline_cond); + for (p, a, e) in cfgs_at(spans.get_or_insert_with(|| cfg_spans(&m, src.as_bytes())), at) { + preds.push(p); + at_lines.extend(lines.of(a)..=lines.of(e)); + } + each.push(preds); + } + let preds = match each.len() { + 0 => return None, + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::<Vec<_>>().join(","))], + }; + Some((preds, at_lines)) +} + +/// The file a `#[path = "<rel>"]` declaration in the file `dir/file` loads. Outside inline modules +/// `rel` is relative to the file's directory; inside them (`chain`, outermost first), to the inline +/// modules' directory under the file's module. +fn override_path(dir: &str, file: &str, mod_rs: bool, chain: &[String], rel: &str) -> String { + let mut base = dir.to_owned(); + if !chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + +/// The files that `#[path]` declarations in `src`, the file `parent`, load, each with the inline +/// modules its declaration sits in. +fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> { + let m = mask(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = owns_its_dir(parent); + let mut out = vec![]; + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let rels = + path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r)); + let chains: Vec<Vec<String>> = inline_routes(&m, src.as_bytes(), at).into_iter().map(|(chain, _)| chain).collect(); + for rel in rels { + for chain in &chains { + out.push((override_path(dir, file, mod_rs, chain, &rel), chain.clone())); + } + } + } + out +} + +/// The files that load a module file through `#[path]`, keyed by the file they load: a sibling such +/// as `graphics.rs` loading `tests_graphics.rs` is not among the files [`module_parent`] names. +type Overrides = HashMap<String, Vec<(String, Vec<String>)>>; + +/// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. +fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { + let with_path = match base { + // `-z` lists each path verbatim, NUL-terminated: without it Git quotes a non-ASCII path. + Some(base) => git(root, &["grep", "-z", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "-z", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + } + .unwrap_or_default(); + listed_path_overrides(&with_path, base, read) +} + +/// Read paths from `git grep -z -l` (NUL-separated), removing the revision prefix for a base-tree listing. +fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { + let prefix = base.map(|b| format!("{b}:")); + let sources: Vec<(String, String)> = list + .split('\0') + .filter(|p| !p.is_empty()) + .filter_map(|p| match &prefix { + Some(prefix) => p.strip_prefix(prefix), + None => Some(p), + }) + .filter(|p| is_scanned(p)) + .filter_map(|p| read(p).map(|s| (p.to_owned(), s))) + .collect(); + path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))) +} + +/// [`Overrides`] for the files `sources`, as `(path, source)` pairs. +fn path_overrides<'a>(sources: impl IntoIterator<Item = (&'a str, &'a str)>) -> Overrides { + let mut out: Overrides = HashMap::new(); + for (parent, src) in sources { + if !src.contains("path") { + continue; + } + for (child, chain) in path_children(src, parent) { + // One entry per parent and inline modules: [`declared_cfgs`] joins the declarations of + // one file in one module. + let routes = out.entry(child).or_default(); + if !routes.iter().any(|(p, c)| p == parent && *c == chain) { + routes.push((parent.to_owned(), chain)); + } + } + } + out +} + +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). +fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> { + words(m, b"path", from, to).into_iter().find_map(|at| { + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + let eq = skip_ws(m, at + 4); + let mut q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') { + return None; + } + let hashes = if m.get(q) == Some(&b'r') { + let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); + q += 1 + h; + h + } else { + 0 + }; + if m.get(q) != Some(&b'"') { + return None; + } + let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(m, &close, q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) + }) +} + +/// The value of a whitespace-free `path=<literal>` argument, for an ordinary or a raw string literal. +fn path_arg(arg: &str) -> Option<&str> { + whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +} + +/// The `#[cfg_attr(<condition>, path = "…")]` overrides in `m[from..to]`, each as its condition and +/// path. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) { + continue; + } + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let text = pred_text(&src[open + 1..close]); + let cuts = attr_commas(&text); + let Some(&first) = cuts.first() else { continue }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = path_arg(arg) { + out.push((text[..first].to_owned(), rel.to_owned())); + } + start = cut + 1; + } + } + out +} + +/// `rel` joined to the directory `base`, with `.` and `..` resolved. +fn join_path(base: &str, rel: &str) -> String { + let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// The directory segments of the inline `mod <name> { … }` blocks around `at` in the masked text +/// `m` (`src` unmasked), outermost first. A `mod x;` inside them loads a file under their directory +/// instead of a sibling file. A block's directory is its name, or the value of a `#[path]` on it +/// (`#[path = "platform_impl"] mod platform { mod child; }` loads `platform_impl/child.rs`). A +/// `#[cfg_attr(<condition>, path = "…")]` on a block gives one route per directory: its path where +/// the condition holds, and the default elsewhere. Each route comes with the conditions it needs; +/// at most [`MAX_INLINE_ROUTES`] are kept. +fn inline_routes(m: &[u8], src: &[u8], at: usize) -> Vec<(Vec<String>, Vec<String>)> { + let mut routes: Vec<(String, Vec<String>)> = vec![(String::new(), vec![])]; + for open in (0..at).filter(|&open| m[open] == b'{' && matching(m, open).is_some_and(|close| close > at)) { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + continue; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let seg = path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()); + let conditional = cfg_attr_paths(m, src, item, kw); + let mut options: Vec<(String, Vec<String>)> = conditional.iter().map(|(c, rel)| (rel.clone(), vec![c.clone()])).collect(); + let fallback = + (!conditional.is_empty()).then(|| format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))); + options.push((seg, fallback.into_iter().collect())); + routes = routes + .iter() + .flat_map(|(dir, conds)| options.iter().map(move |(seg, c)| (join_path(dir, seg), conds.iter().chain(c).cloned().collect()))) + .take(MAX_INLINE_ROUTES) + .collect(); + } + routes.into_iter().map(|(dir, conds)| (dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect(), conds)).collect() +} + +/// The most routes [`inline_routes`] follows through nested conditional directories. +const MAX_INLINE_ROUTES: usize = 16; + +/// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the +/// modules above it, read through `read`. +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Vec<String>> { + module_gates(paths, read, overrides).into_iter().map(|(p, g)| (p, g.preds)).collect() +} + +/// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares +/// them, the lines of those declarations and attributes. +#[derive(Default)] +struct Gates { + preds: Vec<String>, + sources: Vec<(String, Vec<usize>)>, + /// Whether a crate target loads the file through at least one route. + reached: bool, +} + +/// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that +/// may declare its module and in the files above them through inline modules +/// (`mod platform { mod child; }` loads `platform/child.rs`), and in the files of `overrides` that +/// load it through `#[path]`. +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Gates> { + let read = cached_read(read); + paths + .iter() + .filter_map(|path| { + let gates = module_gate(path, &read, overrides, 0, Via::Any); + (!gates.preds.is_empty()).then(|| (path.clone(), gates)) + }) + .collect() +} + +/// Which routes to a file [`module_gate`] follows: a file that is not a `mod.rs` or a crate root +/// declares its modules in a directory named after it when a `mod <name>;` loads it (`Named`), and +/// in its own directory when a `#[path]` loads it (`Path`). +#[derive(Clone, Copy, PartialEq)] +enum Via { + Any, + Named, + Path, +} + +/// Resolve each route's ancestors before joining routes, with a bound for cyclic module paths. +fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides, depth: usize, via: Via) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; + } + let by_path = if via == Via::Named { &[][..] } else { overrides.get(at).map_or(&[][..], Vec::as_slice) }; + // A crate root runs independently of any module declarations that also load it. + let Some((name, mut candidates)) = module_parent(at) else { + gates.reached = true; + return gates; + }; + let name = name.to_owned(); + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + gates.reached = true; + return gates; + }; + let mut chain: Vec<String> = vec![]; + // Each file that loads the module, what it declares, and the routes to it that load the module + // from there. + let mut found = vec![]; + // Whether a file that could declare the module exists: when none does, the module's parent is + // unknown and the file counts as reached. + let mut parent_read = false; + // A parent that is neither a `mod.rs` nor a crate root loads the module only through its + // `mod <name>;` routes. + let named = |c: &str| if owns_its_dir(c) { Via::Any } else { Via::Named }; + for _ in 0..4 { + let want = Loaded { path: at, name: &name, chain: &chain }; + // Every file that loads the module is another way in (a library and a binary root + // can both load it): its tests are off only when every one of them leaves them out. + if via != Via::Path { + found.extend(candidates.iter().filter_map(|c| { + read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c))) + })); + } + if chain.is_empty() { + for (c, inline) in by_path { + // A candidate was read with no inline modules; another route through the + // same file still counts. + if via != Via::Path && inline.is_empty() && candidates.contains(c) { + continue; + } + let want = Loaded { path: at, name: &name, chain: inline }; + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any))); + } + // A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;` + // loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`). + let path_loaded = overrides + .keys() + .filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir)); + for owner in path_loaded { + found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path))); + } + } + if via == Via::Path || beside_roots(at) { + break; + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + let mut each = vec![]; + // Through `#[path]` alone, a file no `#[path]` declaration loads is not reached. + gates.reached = found.is_empty() && !parent_read && via != Via::Path; + for (parent, (mut preds, lines), parent_via) in found { + let ancestors = module_gate(&parent, read, overrides, depth + 1, parent_via); + // A parent that no crate target loads (a file left on disk after its `mod` line was + // removed) is not a route, so it cannot stand in for an ungated one. + if !ancestors.reached { + continue; + } + gates.reached = true; + preds.extend(ancestors.preds); + gates.sources.push((parent, lines)); + gates.sources.extend(ancestors.sources); + each.push(preds); + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::<Vec<_>>().join(","))], + }; + gates +} + +/// A test that a `cfg` compiles out on every target CI runs tests on. +fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> { + let local = cfgs_at(&v.file.cfgs, v.t.fn_at); + // A change to an attribute that turns the test off counts as a change to the test, on any line + // of a multiline attribute. + // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) does + // not turn the test off, so its lines do not count. + let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); + let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); + let attr_lines: Vec<usize> = + local.iter().filter(|(p, _, _)| excludes(p)).flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec<String> = local.into_iter().map(|(p, _, _)| p).collect(); + preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); + if preds.is_empty() { + return None; + } + let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false)); + if CI_TARGETS.iter().chain(windows).all(off) { + let shown: Vec<String> = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); + let mut note = format!("{} leaves it out of every target CI tests on", shown.join(", ")); + let mut builds: Vec<&str> = PLATFORM_TARGETS.iter().filter(|(_, t)| !off(t)).map(|(name, _)| *name).collect(); + builds.dedup(); + if !builds.is_empty() { + note += &format!("; it builds on {}, so run it there", builds.join(" and ")); + } + let mut hit = v.whole(Rule::NeverRun, note); + hit.report_only = !builds.is_empty(); + // Enclosing attributes count as separate lines, so an edit to code between them and the + // test does not count. + hit.gates = attr_lines.into_iter().filter(|&l| l < hit.first).collect(); + return Some(hit); + } + None +} + +/// What may follow a screen rect in an exact-pixel comparison: a corner, an edge or a size. +const RECT_PARTS: &[&str] = &[ + ".min", + ".max", + ".left_top()", + ".right_bottom()", + ".center()", + ".size()", + ".width()", + ".height()", + ".left()", + ".right()", + ".top()", + ".bottom()", +]; + +/// Whether a whitespace-free operand reads a screen rect: an identifier `rect`, or one that starts +/// with `rect_` or ends with `_rect` (a call to one included), taken whole or through +/// [`RECT_PARTS`]. Document geometry (artboards, `x0`/`y0` corners, a document's nodes) and a rect +/// passed on as an argument do not count. +fn names_rect(op: &str) -> bool { + if ["artboard", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + return false; + } + let document = |w: &str| w == "doc" || w == "document" || w.starts_with("doc_") || w.ends_with("_doc"); + if op.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(document) { + return false; + } + let b = op.as_bytes(); + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) { + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let w = &op[i..end]; + if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") { + let mut after = end; + if b.get(after) == Some(&b'(') { + after = matching(b, after).map_or(b.len(), |c| c + 1); + } + // The rect and its parts make up the whole operand: `a.width() - b.width()` compares two + // rects, not one with a number. + let mut rest = &op[after..]; + while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) { + rest = r; + } + // Only grouping parentheses may surround it: in `count_items(button_rect)` the rect is a + // call's argument, and the operand is what the call returns. + let lead = op[..i].trim_start_matches(['&', '*']); + let lb = lead.as_bytes(); + let call = (1..lb.len()).any(|k| lb[k] == b'(' && (is_ident(lb[k - 1]) || matches!(lb[k - 1], b'!' | b'>'))); + let groups = lead.matches('(').count(); + let path = lead.trim_start_matches(['&', '*', '(']); + if !call && rest.len() == groups && rest.bytes().all(|c| c == b')') && !path.contains(['+', '-', '*', '/', '%', ',', '(']) { + return true; + } + } + i = end; + } + false +} + +/// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. +fn only_numbers(op: &str) -> bool { + let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); + for builder in ["Rect::from_min_max", "Rect::from_min_size", "Rect::from_center_size", "Pos2::new", "Vec2::new", "pos2", "vec2", "Some"] { + rest = rest.replace(builder, ""); + } + let rest = rest.replace("f32", ""); + rest.bytes().any(|c| c.is_ascii_digit()) && rest.bytes().all(|c| c.is_ascii_digit() || b".,()-+_".contains(&c)) +} + +/// An assertion in a UI test that a rect, or a coordinate or size of one, equals numbers written out. +fn exact_pixels(v: &View) -> Vec<Hit> { + if !contains(&v.file.m, b"egui") { + return vec![]; + } + v.asserts + .iter() + .filter_map(|a| { + let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t])); + let (l, r) = if a.name.ends_with("_eq") { + (arg(0)?, arg(1)?) + } else if PLAIN_ASSERTS.contains(&a.name.as_str()) { + let cond = arg(0)?; + let at = *top_level_at(&cond, "==").first()?; + (cond[..at].to_owned(), cond[at + 2..].to_owned()) + } else { + return None; + }; + let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); + pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { ci_env: ["SET_IN_CI".to_owned()].into_iter().collect(), ..Ctx::default() } + } + + /// The rule ids of `src`'s hits, as `(line, rule)`. + fn hits(src: &str) -> Vec<(usize, &'static str)> { + hits_in("crates/x/src/tests.rs", src, &ctx()) + } + + fn hits_in(path: &str, src: &str, ctx: &Ctx) -> Vec<(usize, &'static str)> { + lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() + } + + #[test] + fn all_needs_a_non_empty_guard() { + let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); + let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; + assert_eq!(hits(none), [], "all(|w| !…) says that no item matches"); + let other = "#[test]\nfn t() {\n assert!(listed().iter().all(|e| e[\"id\"] != id));\n assert!([0, 4, 20].iter().all(|&i| glow[i].a() == 0));\n}\n"; + assert_eq!(hits(other), [], "one != comparison, and an array literal"); + let indexed = "#[test]\nfn t() {\n assert!(rows()[2].iter().all(|r| r.ok && r.n != 0));\n assert!(f().iter().all(|x| x.0 != 1 && x.1 != 2));\n}\n"; + assert_eq!(hits(indexed), [(3, "all-unguarded")]); + let mixed = "#[test]\nfn t() {\n assert!(f().iter().all(|x| x.0 != 1 && x.1 > 2));\n}\n"; + assert_eq!(hits(mixed), [(3, "all-unguarded")]); + } + + #[test] + fn census_round_trips_look_up_the_entry() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; + assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n"; + assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); + let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; + assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n"; + assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry"); + let field = + "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; + assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); + let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(derived), [(2, "census")]); + let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; + assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); + } + + #[test] + fn census_loops_over_whole_tables_are_reported() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let consts = "#[test]\nfn t() {\n for c in COLORS.iter() {\n assert!(!c.name.is_empty());\n }\n}\n"; + assert_eq!(census(consts), [(2, "census")]); + let round = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(round), [(2, "census")]); + let call = "#[test]\nfn t() {\n for p in builtin_presets() {\n assert!(lookup(&p.name).is_some());\n }\n}\n"; + assert_eq!(census(call), [(2, "census")]); + let all = "#[test]\nfn t() {\n assert!(Swatch::iter().all(|s| s.rgb().is_some()));\n}\n"; + assert_eq!(census(all), [(2, "census")]); + let behavior = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(apply(k, 2), 4);\n }\n}\n"; + assert_eq!(census(behavior), [], "a computed result for each entry is a real check"); + let mixed = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n assert_eq!(blend(c), WHITE);\n }\n}\n"; + assert_eq!(census(mixed), [], "one real assertion in the loop keeps it"); + let joined = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && blend(c) == WHITE);\n }\n assert!(Swatch::iter().all(|s| s.rgb().is_some() && s.rgb() != BLACK));\n}\n"; + assert_eq!(census(joined), [], "a presence guard joined to a real check"); + let both = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && !c.name.is_empty());\n }\n}\n"; + assert_eq!(census(both), [(2, "census")]); + let few = "#[test]\nfn t() {\n for c in COLORS.iter().take(2) {\n assert!(c.is_some());\n }\n for c in &COLORS[..2] {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(few), [], "a few representative entries"); + let expected = "#[test]\nfn t() {\n for case in CASES {\n assert_eq!(parse(case.input), case.expected);\n assert_eq!(sparse(case), case);\n }\n}\n"; + assert_eq!(census(expected), [], "an expected value written in the table, and a name that only ends in parse"); + let helper = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n check_render(c);\n }\n}\n"; + assert_eq!(census(helper), [], "an asserting helper in the loop"); + let local = "#[test]\nfn t() {\n for x in xs.iter() {\n assert!(x.is_some());\n }\n}\n"; + assert_eq!(census(local), [], "a local collection is not a table"); + let allowed = "// test-lint: allow census every command needs a menu path\n#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some());\n }\n}\n"; + assert_eq!(census(allowed), []); + for ne in ["assert_ne!(Kind::from_id(k.id()), Some(k))", "debug_assert_ne!(lookup(k), k)", "prop_assert_ne!(Kind::parse(k.name()), Ok(k))"] { + let rejects = format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n {ne};\n }}\n}}\n"); + assert_eq!(census(&rejects), [], "an inequality is not a round trip: {ne}"); + } + let borrowed = "#[test]\nfn t() {\n for k in &Kind::ALL {\n assert_eq!(Kind::from_id(k.id()).as_ref(), Some(k));\n }\n}\n"; + assert_eq!(census(borrowed), [(2, "census")]); + let both_all = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && LABELS.iter().all(|s| !s.is_empty()));\n}\n"; + assert_eq!(census(both_all), [(2, "census")]); + let either = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || actual == expected);\n}\n"; + assert_eq!(census(either), [(2, "census")], "an || lets the presence branch pass alone"); + let long = format!( + "#[test]\nfn t() {{\n assert!(COLORS.iter().all(|c| c.is_some()){});\n}}\n", + "&&COLORS.iter().all(|c|c.is_some())".repeat(200) + ); + assert_eq!(census(&long), [], "a chain deeper than the limit is not judged"); + let inner = "#[test]\nfn t() {\n for a in COLORS.iter().map(|c| c.aliases.iter().filter_map(|a| a.id()).next()) {\n assert!(a.is_some());\n }\n}\n"; + assert_eq!(census(inner), [(2, "census")]); + let accented = "#[test]\nfn t() {\n for c in COLORS.iter().clonés() {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(accented), [(2, "census")], "a non-ASCII method name is read without panicking"); + let nested = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| c.parts.iter().all(|p| p.ok)).all(|c| c.is_some()));\n}\n"; + assert_eq!(census(nested), [(2, "census")]); + let wrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Some(Kind::parse(k.name()).unwrap()), Some(k));\n }\n}\n"; + assert_eq!(census(wrapped), [(2, "census")]); + let derived = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(parse(&src(n)).unwrap().children.len(), n);\n }\n}\n"; + assert_eq!(census(derived), [], "a value derived from the parsed entry is a real check"); + let unwrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(unwrapped), [(2, "census")]); + let all_joined = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && actual == expected);\n}\n"; + assert_eq!(census(all_joined), [], "an .all(…) presence check joined to a real check"); + let subsets = "#[test]\nfn t() {\n for c in COLORS.iter().filter_map(|c| c.alt) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().take_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().skip_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().map_while(|c| c.alt) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(subsets), [], "subset adapters pick a few entries"); + } + + #[test] + fn census_skips_derived_lookups_and_deep_nesting() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let referenced = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(mask & lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(referenced), [], "a bitwise and before the lookup derives a value"); + let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(qualified), [(2, "census")]); + let deep = + format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66)); + assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged"); + } + + #[test] + fn census_skips_loops_bounded_by_zip_or_flat_map() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop"); + let ranged = "#[test]\nfn t() {\n for (c, i) in COLORS.iter().zip(0..2) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(ranged), [], "a range zipped in bounds the loop"); + for range in ["0..", "0..,", "(0..)", "((0..)),", "std::iter::repeat(0..2)"] { + let open = format!("#[test]\nfn t() {{\n for (c, i) in COLORS.iter().zip({range}) {{\n assert!(c.is_some());\n }}\n}}\n"); + assert_eq!(census(&open), [(2, "census")], "an open-ended range zipped in visits every entry: {range}"); + } + let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n"; + assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop"); + } + + #[test] + fn census_counts_rejections_and_helpers_as_checks() { + let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n"; + assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection"); + let spaced = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err ();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err (\"rejects\");\n }\n}\n"; + assert_eq!(census_in(spaced, &ctx()), [], "whitespace inside the rejection call"); + let all_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| parse(c.bad).unwrap_err().contains(\"bad\")));\n assert!(CASES.iter().all(|c| parse(c.bad).expect_err(\"rejects\").contains(\"bad\")));\n}\n"; + assert_eq!(census_in(all_rejects, &ctx()), [], "an unwrap_err or expect_err in the .all(…) predicate checks a rejection"); + let skips = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some() || parse(c.bad).unwrap_err().contains(\"bad\")));\n}\n"; + assert_eq!(census_in(skips, &ctx()), [(2, "census")], "a rejection after a presence check on an || can be skipped"); + let first = "#[test]\nfn t() {\n assert!(parse(invalid).unwrap_err().contains(\"bad\") || CASES.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(first, &ctx()), [], "a rejection on the left of an || always runs"); + let and_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some()) && parse(invalid).unwrap_err().is_empty());\n}\n"; + assert_eq!(census_in(and_rejects, &ctx()), [], "a rejection on the other side of an && always runs"); + let broken = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n break;\n }\n}\n"; + assert_eq!(census_in(broken, &ctx()), [], "a break can end the loop before the last entry"); + assert_eq!(census_in(&broken.replace(" break;\n", ""), &ctx()), [(2, "census")]); + let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n"; + assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]); + let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n"; + let files = [("crates/x/src/tests.rs".to_owned(), all_helper.to_owned())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(census_in(all_helper, &with_helpers), [], "an asserting helper in the .all(…) predicate"); + assert_eq!(census_in(all_helper, &ctx()), [(2, "census")], "a predicate whose call does not assert"); + let message = + "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok(),\"{:?}\", probe().unwrap_err());\n }\n}\n"; + assert_eq!(census_in(message, &ctx()), [(2, "census")], "an unwrap_err in a failure message runs only after a failure"); + let skipped = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || verify_fallback());\n}\n"; + assert_eq!(census_in(skipped, &ctx()), [(2, "census")], "a helper on the other side of an || can be skipped"); + let inner = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some() || verify_fallback(c).is_some()));\n}\n"; + assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped"); + let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); + let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; + assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); + let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; + assert_eq!(census_in(first, &ctx()), [], "a helper on the left of an || always runs"); + let generic = all_helper.replace("exercise(c)", "exercise::<Color>(c)"); + assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish"); + let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n"; + assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); + let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry"); + assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); + let sourced = "#[test]\nfn t() {\n for c in COLORS.iter().map(|c| { verify_entry(c); c }) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census_in(sourced, &ctx()), [], "a helper in the loop source runs for every entry"); + assert_eq!(census_in(&sourced.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); + let refused = "#[test]\nfn t() {\n for case in CASES {\n assert!(!parse(case.invalid).is_ok());\n }\n for case in CASES {\n assert!(!lookup(case.missing).is_some());\n }\n}\n"; + assert_eq!(census_in(refused, &ctx()), [], "a negated is_ok or is_some checks a rejection"); + let filled = "#[test]\nfn t() {\n for c in COLORS {\n assert!(!c.name.is_empty());\n }\n}\n"; + assert_eq!(census_in(filled, &ctx()), [(2, "census")]); + } + + #[test] + fn census_is_report_only() { + assert!(!Rule::Census.fails()); + assert_eq!(Rule::from_id("census"), Some(Rule::Census)); + } + + #[test] + fn all_equality_guards_match_each_receiver() { + for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { + for operand in ["xs", "&xs", "xs.as_slice()", "&xs.as_slice()", "xs[..]", "&xs[..]"] { + for literal in ["[1]", "[1, 2,]", "[1; 2]", "vec![1, 2]", "vec![1; 2]", "[\"[;]\", name]"] { + for (left, right) in [(operand, literal), (literal, operand)] { + let src = format!( + "#[test]\nfn t() {{\n {assertion}!({left}, {right}, \"items\");\n assert!(xs.iter().all(|x| valid(x)));\n assert!(ys.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{assertion}!({left}, {right})"); + let combined = src.replace("valid(x)));\n assert!(ys", "valid(x)) && ys"); + assert_eq!(hits(&combined), [(4, "all-unguarded")], "another receiver in the same condition"); + } + } + } + } + } + + #[test] + fn all_equality_guards_require_non_empty_literals() { + for expected in ["[]", "[1; 0]", "vec![]", "vec![1; 0]", "expected", "items()", "[1].map(f)", "vec![1].clone()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); + } + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.filter(f)", "xs.iter().filter(f).collect()", "xs[1..]", "&&xs"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); + } + } + + #[test] + fn all_equality_guards_require_earlier_compared_operands_in_the_test() { + for assertion in ["assert_ne", "debug_assert_ne", "prop_assert_ne"] { + let src = format!("#[test]\nfn t() {{\n {assertion}!(xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{assertion}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n assert_eq!(xs, [1]);\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")]); + let outside = "fn helper() { assert_eq!(xs, [1]); }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")]); + let message = "#[test]\nfn t() {\n assert_eq!(a, b, \"items {:?} {:?}\", xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(message), [(4, "all-unguarded")]); + } + + #[test] + fn all_skips_conjunctions_of_not_equal_comparisons() { + for predicate in [ + "|(id, _)| id != \"action.batch\" && id != \"flattener.preview\"", + "|x| x.0 != 1 && x.1 != 2", + "|x| x != 1 && x != 2 && x != 3", + "|x| (x != 1) && ((x != 2) && x != 3)", + "|x| value(x) != expected(1, 2) && *x != 3", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + let mixed = src.replace("));\n", ") && ys.iter().all(|y| valid(y)));\n"); + assert_eq!(hits(&mixed), [(3, "all-unguarded")], "another positive predicate beside {predicate}"); + } + } + + #[test] + fn all_reports_conjunctions_with_other_predicates() { + for predicate in [ + "|x| x != 1 && x == 2", + "|x| x != 1 && x < 2", + "|x| x.0 != 1 && x.1 > 2", + "|x| x != 1 && valid(x)", + "|x| valid(x) && x != 1", + "|x| x != 1 || x != 2", + "|x| x != 1 && x != 2 || x != 3", + "|x| x != 1 && (x != 2 || x != 3)", + "|x| (x != 1 && x > 2) && x != 3", + "|x| valid(x != 1) && x != 2", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_only_whole_negations_and_not_equal_conjunctions() { + for predicate in [ + "|x| !x.contains(\"lost\")", + "|x| !blocked!(x)", + "|x| !(blocked(x) && invalid(x))", + "|x| !a(x) && !b(x)", + "|x| !a(x) && x != 1", + "|x| x != 1 && (!a(x) && !(b(x)))", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + } + for predicate in [ + "|x| !blocked(x) && valid(x)", + "|x| valid(x) && !blocked(x)", + "|x| !a(x) || b(x)", + "|x| !a(x) == b(x)", + "|x| (!a(x) == b(x)) && x != 1", + "|x| !a(x) && (!b(x) || c(x))", + "|x| !a(x) ^ b(x)", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_locally_bound_non_empty_arrays() { + for binding in [ + "let xs = [1, 2];", + "let mut xs = [1, 2];", + "let xs: [u8; 2] = [1, 2];", + "let mut xs: [u8; 2] = [1, 2];", + "let xs = [1; 2];", + "let xs = [[1, 2], [3, 4]];", + "let xs = [\"[\", \";\", \"bad ] brackets [\"].map(|s| s.trim());", + "let xs = [1, 2].map(|x| { let pair = [x, x]; pair });", + "let xs /* items */ : [u8; 2] = [1, 2] . map (|x| x + 1);", + ] { + for method in ["iter", "into_iter"] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding} through {method}"); + let mixed = src.replace("valid(x)))", "valid(x)) && ys.iter().all(|y| valid(y)))"); + assert_eq!(hits(&mixed), [(4, "all-unguarded")], "another collection beside {binding}"); + } + } + } + + #[test] + fn all_reports_empty_arrays_and_other_initializers() { + for value in [ + "[]", + "[1; 0]", + "[1; 0].map(|x| x + 1)", + "vec![]", + "vec![1; 0]", + "vec![1; n]", + "items()", + "items().collect()", + "items().collect::<Vec<_>>()", + "(0..0).collect::<Vec<_>>()", + "(3..1).collect::<Vec<_>>()", + "(0..n).collect::<Vec<_>>()", + "(0..).take(3).collect::<Vec<_>>()", + "[1, 2].iter().filter(|x| keep(x)).collect::<Vec<_>>()", + "[1, 2].into_iter().zip(ys).collect::<Vec<_>>()", + "[None::<u8>].into_iter().collect::<Option<Vec<_>>>()", + "[Err::<u8, E>(error())].into_iter().collect::<Result<Vec<_>, E>>()", + "[1, 2].into_iter().collect()", + "[1, 2].into_iter().collect::<Items>()", + "[1, 2].into_iter().collect::<unknown::Vec<_>>()", + ] { + for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding}"); + } + } + } + + #[test] + fn all_array_bindings_match_only_plain_preceding_local_names() { + for (binding, receiver) in [ + ("let xs_other = [1, 2];", "xs"), + ("let other_xs = [1, 2];", "xs"), + ("let (xs, ys) = ([1, 2], items());", "xs"), + ("let xs = [1, 2]; let xs = items();", "xs"), + ("let xs = [1, 2];", "other.xs"), + ("let xs = [1, 2];", "other::xs"), + ("let xs = [1, 2];", "xs()"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!({receiver}.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding} with {receiver}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n let xs = [1, 2];\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")], "a later binding does not initialize the receiver"); + let outside = "fn helper() { let xs = [1, 2]; }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")], "a binding outside the test does not count"); + } + + #[test] + fn all_direct_array_literals_must_be_non_empty() { + for method in ["iter", "into_iter"] { + for array in ["[]", "[1; 0]", "[items(); 0]", "[1; 0usize]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{array} through {method}"); + } + for array in ["[1]", "[1, 2]", "[1; 2]", "[[1; 0]]", "[\"[;]\"]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{array} through {method}"); + } + } + } + + #[test] + fn all_skips_mapped_arrays_of_named_rectangles() { + for (name, labels, message) in [ + ("chips", "[\"Color (, or Shift+,)\", \"Gradient (. or Shift+.)\", \"None (/)\"]", "one line"), + ("modes", "[\"Draw Normal (Shift+D)\", \"Draw Behind (Shift+D)\", \"Draw Inside (Shift+D)\"]", "side by side"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let {name} = {labels}.map(|label| named_rect(&nodes, label));\n assert!({name}.iter().all(|r| (r.top() - {name}[0].top()).abs() < 0.5), \"{message}: {{{name}:?}}\");\n}}\n" + ); + assert_eq!(hits(&src), [], "{name}"); + let empty = src.replace(labels, "[]"); + assert_eq!(hits(&empty), [(4, "all-unguarded")], "an empty {name} still passes vacuously"); + } + } + + #[test] + fn all_skips_bindings_with_sized_initializers() { + let consts = "const N: usize = 3;\nconst NONE: usize = 0;\n"; + for binding in [ + "let xs = vec![1, 2];", + "let mut xs = vec![[1, 2]; 2];", + "let xs: Vec<_> = [1, 2].into_iter().collect();", + "let xs = [1, 2].map(|x| x + 1).map(|x| x + 1);", + "let xs: Vec<u8> = [1, 2].iter().copied().rev().collect();", + "let xs: Vec<Px> = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::<Vec<_>>();", + "let xs = (-2..1).step_by(2).collect::<Vec<_>>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::<Vec<_>>().into_iter().collect();", + "let xs = [0.0; N];", + "let xs: [u8; 3] = items();", + "let xs: [u8; N] = items();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")], "{binding} then cleared"); + } + for binding in [ + "let xs = (0..NONE).collect::<Vec<_>>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::<Vec<_>>();", + "let xs = [None::<u8>].into_iter().collect::<Option<Vec<_>>>();", + "let xs = [Err::<u8, E>(error())].into_iter().collect::<Result<Vec<_>, E>>();", + "let xs: Option<Vec<u8>> = [1].into_iter().collect();", + "let xs: Result<Vec<u8>, E> = [1].into_iter().collect();", + "let xs = [1, 2].into_iter().collect();", + "let xs: Items = [1, 2].into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect().clone();", + "let xs: Vec<_> = [1, 2].into_iter().collect().into_iter().collect();", + "let xs: Vec<_> = [None::<u8>].into_iter().collect::<Option<Vec<_>>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::<Items>();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "{binding}"); + } + for later in [ + "xs.retain(|x| keep(x));", + "xs = items();", + "take(&mut xs);", + "xs.truncate(0);", + "xs.pop();", + "xs.resize(0, 0);", + "xs.resize_with(0, f);", + "xs.pop_front();", + "xs.pop_back();", + "xs.unknown_method_that_may_shrink();", + "xs . unknown::<T>();", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{later}"); + } + for op in ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="] { + let src = + format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n xs {op} other;\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{op}"); + } + for later in [ + "xs[0] = 5; use_it(&xs);", + "xs[1] = 5; use_it(&xs);", + "use_it(&xs);", + "use_it(xs);", + "use_it(xs == other);", + "match other { xs => use_it(xs), _ => () };", + "xs.push(3); xs.push_back(4); xs.push_front(5); xs.insert(0, 6); xs.extend(other);", + "xs.sort(); xs.sort_by(f); xs.sort_by_key(f); xs.sort_unstable(); xs.reverse();", + "use_it(xs.iter()); use_it(xs.iter_mut()); use_it(xs.into_iter());", + "use_it(xs.len()); use_it(xs.is_empty()); use_it(xs.contains(&1));", + "use_it(xs.get(0)); use_it(xs.get_mut(0)); use_it(xs.first()); use_it(xs.last());", + "use_it(xs.first_mut()); use_it(xs.last_mut()); use_it(xs.as_slice()); use_it(xs.as_ref());", + "use_it(xs.clone()); use_it(xs.to_vec()); use_it(xs.windows(2)); use_it(xs.chunks(2));", + "use_it(xs.binary_search(&1)); use_it(xs.starts_with(&[1])); use_it(xs.ends_with(&[2]));", + "use_it(xs.map(f)); use_it(xs.concat()); use_it(xs.join(sep)); use_it(xs.keys()); use_it(xs.values());", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{later}"); + } + } + + #[test] + fn all_collects_require_known_collection_targets() { + for target in [ + "Vec<_>", + "std::vec::Vec<_>", + "VecDeque<_>", + "std::collections::VecDeque<_>", + "HashSet<_>", + "std::collections::HashSet<_>", + "BTreeSet<_>", + "std::collections::BTreeSet<_>", + "HashMap<_, _>", + "std::collections::HashMap<_, _>", + "BTreeMap<_, _>", + "std::collections::BTreeMap<_, _>", + "BinaryHeap<_>", + "std::collections::BinaryHeap<_>", + "LinkedList<_>", + "std::collections::LinkedList<_>", + "String", + "std::string::String", + "Box<[_]>", + "std::boxed::Box<[_]>", + ] { + let source = if target.contains("Map") { "[(1, 2)]" } else { "['a', 'b']" }; + for binding in [ + format!("let xs = {source}.into_iter().collect::<{target}>();"), + format!("let xs: {target} = {source}.into_iter().collect();"), + format!("let xs = {source}.into_iter().collect::<{target}>().into_iter().collect::<Vec<_>>();"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + } + } + } + + #[test] + fn all_skips_collections_every_pass_of_a_sized_loop_fills() { + for (source, fill) in [ + ("[1, 2, 3]", "xs.push(i);"), + ("0..3", "xs.push(i);"), + ("[[0, 1], [1, 0]]", "let s = Fill { a: 1 }.span(i);\n xs.push(s);"), + ("[1, 2].iter().enumerate()", "for j in items() { use_it(j); }\n xs.insert(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{source}: {fill}"); + let after = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&after), [(line + 1, "all-unguarded")], "{source} then cleared"); + } + for (source, fill) in [ + ("items()", "xs.push(i);"), + ("0..0", "xs.push(i);"), + ("0..n", "xs.push(i);"), + ("[1, 2]", "if keep(i) { xs.push(i); }"), + ("[1, 2]", "if !keep(i) { continue; }\n xs.push(i);"), + ("[1, 2]", "let v = get(i)?;\n xs.push(v);"), + ("[1, 2]", "ys.iter().for_each(|y| xs.push(*y));"), + ("[1, 2]", "ys.push(i);"), + ("[1, 2]", "let mut xs = vec![];\n xs.push(i);"), + ("[1, 2].iter().filter(|x| keep(x))", "xs.push(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{source}: {fill}"); + } + let nested = "#[test]\nfn t() {\n let mut xs = vec![];\n if ready() {\n for i in [1, 2] {\n xs.push(i);\n }\n }\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(nested), [(9, "all-unguarded")], "a loop that may not run"); + } + + #[test] + fn all_skips_fields_the_file_declares_as_arrays() { + let test = "#[test]\nfn t() {\n let c = parse();\n assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));\n}\n"; + for decl in [ + "struct C { rgb: [f32; 3] }\n", + "const N: usize = 3;\nstruct C { pub rgb: [f32; N], alpha: Option<f32> }\n", + "struct C { rgb: [f32; 3] }\nfn c() -> C { C { rgb: rgb_of(\"x\"), alpha: 1 } }\n", + ] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{decl}"); + let other = format!("{decl}struct D {{ rgb: Vec<f32> }}\n{test}"); + assert_eq!(hits(&other), [(line + 1, "all-unguarded")], "another struct's rgb can be empty"); + } + for decl in + ["struct C { rgb: [f32; 0] }\n", "struct C { rgb: &'static [f32] }\n", "struct C { rgb: [f32; LEN] }\n", "struct C { other: [f32; 3] }\n"] + { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{decl}"); + } + for other in ["std::vec::Vec<f32>", "Pixels", "u8", "(f32, f32)", "T"] { + let src = format!("struct C {{ rgb: [f32; 3] }}\nstruct D {{ rgb: {other} }}\n{test}"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "another struct's rgb is {other}"); + } + let local = "struct C { rgb: [f32; 3] }\n#[test]\nfn t() {\n let rgb = parse();\n assert!(rgb.iter().all(|v| valid(v)));\n}\n"; + assert_eq!(hits(local), [(5, "all-unguarded")], "a local name is not the field"); + } + + #[test] + fn all_equality_guards_follow_methods_that_keep_items() { + for operand in [ + "xs.clone()", + "xs.iter().map(|l| l.0).collect()", + "xs.iter().copied().collect::<Vec<_>>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::<Vec<_>>()", + "&xs.iter().copied().rev().collect::<Vec<u8>>()", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, vec![0, 7]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(5, "all-unguarded")], "{operand} then cleared"); + } + for (binding, compared) in [ + ("let ids: Vec<&str> = xs.iter().map(|l| l.id()).collect();", "assert_eq!(ids, [\"a\", \"b\"]);"), + ("let ids = xs.iter().cloned().collect::<Vec<_>>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::<Vec<_>>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::<Vec<_>>().into_iter().collect();", "assert_eq!(ids, [1]);"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n {compared}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let filtered = src.replace(binding, &binding.replace(".iter()", ".iter().filter(|x| keep(x))")); + assert_eq!(hits(&filtered), [(5, "all-unguarded")], "{binding} through a filter"); + let rebound = src.replace(&format!(" {compared}\n"), &format!(" let ids = other();\n {compared}\n")); + assert_eq!(hits(&rebound), [(6, "all-unguarded")], "{binding} then bound again"); + for change in ["ids = vec![1];", "ids.clear();", "reset(&mut ids);", "ids.push(1);"] { + let reassigned = + src.replace("let ids", "let mut ids").replace(&format!(" {compared}\n"), &format!(" {change}\n {compared}\n")); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "{binding} then {change}"); + } + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "{binding} then the source cleared"); + } + } + + #[test] + fn all_equality_guards_stop_at_other_collect_targets() { + for operand in [ + "xs.iter().copied().collect().into_iter().collect::<Vec<_>>()", + "xs.iter().copied().collect().into_iter().collect()", + "xs.iter().copied().collect().clone()", + ] { + for compared in [format!("{operand}, [vec![]]"), format!("[vec![]], {operand}")] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({compared});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{compared}"); + } + } + for binding in [ + "let ids: Option<Vec<u8>> = xs.iter().copied().collect();", + "let ids: Result<Vec<u8>, E> = xs.iter().copied().collect();", + "let ids: Items = xs.iter().copied().collect();", + "let ids = xs.iter().copied().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect::<Vec<_>>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::<Vec<_>>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option<Vec<_>>", "Result<Vec<_>, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::<Vec<_>>()"); + let direct = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&direct), [(4, "all-unguarded")], "{target} compared directly"); + let derived = format!( + "#[test]\nfn t() {{\n let ids = {operand};\n assert_eq!(ids, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&derived), [(5, "all-unguarded")], "{target} through a local"); + } + } + + #[test] + fn all_skips_const_and_static_arrays_of_the_file() { + let test = "#[test]\nfn t() {\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + for decl in [ + "const NAMES: [&str; 2] = [\"a\", \"b\"];\n", + "static NAMES: [u8; N] = [0; N];\nconst N: usize = 4;\n", + "pub(crate) static mut NAMES: [u8; 1] = [0];\n", + ] { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [], "{decl}"); + } + for decl in ["const NAMES: [&str; 0] = [];\n", "const NAMES: &[&str] = &[\"a\"];\n", "fn my_const() {}\nlet NAMES: [u8; 2] = f();\n", ""] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{decl}"); + } + let shadowed = "const NAMES: [&str; 2] = [\"a\", \"b\"];\n#[test]\nfn t() {\n let NAMES = items();\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + assert_eq!(hits(shadowed), [(5, "all-unguarded")], "a local of the same name"); + for (other_type, other_value, found) in [("[u8; 0]", "[]", true), ("&[u8]", "&[]", true), ("[u8; 3]", "[0; 3]", false)] { + for (first_type, first_value, second_type, second_value) in + [("[u8; 2]", "[0; 2]", other_type, other_value), (other_type, other_value, "[u8; 2]", "[0; 2]")] + { + let src = format!( + "mod a {{ const CASES: {first_type} = {first_value}; }}\nmod b {{\nconst CASES: {second_type} = {second_value};\n#[test]\nfn t() {{\n assert!(CASES.iter().all(|n| valid(n)));\n}}\n}}\n" + ); + let want: &[(usize, &str)] = if found { &[(6, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{first_type} and {second_type}"); + } + } + } + + #[test] + fn all_windows_need_as_many_items_as_their_size() { + for (array, method, found) in [ + ("[a, b, c, d]", "windows(2)", false), + ("[a, b]", "windows(2)", false), + ("[a]", "windows(2)", true), + ("[a, b]", "windows(k)", true), + ("[a]", "chunks(3)", false), + ("[a, b]", "chunks_exact(3)", true), + ("[a, b, c]", "chunks_exact(3)", false), + ] { + let src = + format!("#[test]\nfn t() {{\n let xs = {array}.map(|s| node(s));\n assert!(xs.{method}.all(|w| w[0].y == w[1].y));\n}}\n"); + let want: &[(usize, &str)] = if found { &[(4, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{array}.{method}"); + } + } + + #[test] + fn all_guards_accept_asserted_locals_that_count() { + let src = "#[test]\nfn t() {\n let row = cards.iter().filter(|c| first_row(c)).count();\n assert_eq!(row, 4, \"four cards\");\n assert!(cards.iter().all(|c| c.x < 10));\n}\n"; + assert_eq!(hits(src), []); + let summed = src.replace(".count()", ".map(|c| c.w).sum::<u32>()"); + assert_eq!(hits(&summed), [(5, "all-unguarded")], "a sum does not count items"); + let message = src.replace("assert_eq!(row, 4, \"four cards\")", "assert_eq!(a, b, \"{}\", row)"); + assert_eq!(hits(&message), [(5, "all-unguarded")], "a count in a failure message checks nothing"); + let unused = src.replace(" assert_eq!(row, 4, \"four cards\");\n", ""); + assert_eq!(hits(&unused), [(4, "all-unguarded")], "a count no assertion reads checks nothing"); + for change in ["let row = 4;", "row = 4;", "reset(&mut row);"] { + let changed = src.replace(" assert_eq!(row", &format!(" {change}\n assert_eq!(row")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change} before the assertion"); + } + let later = src.replace(" assert_eq!(row, 4, \"four cards\");\n", " assert_eq!(row, 4);\n let row = 4;\n"); + assert_eq!(hits(&later), [], "the count reaches the assertion before it is bound again"); + } + + #[test] + fn all_respects_condition_polarity() { + for condition in [ + "!xs.iter().all(|x| *x > 0)", + "!(xs.iter().all(|x| *x > 0))", + "ready() && !xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) && ready()", + "xs.iter().all(|x| *x > 0) == false", + "ready() && (xs.iter().all(|x| *x > 0) == false)", + "false == xs.iter().all(|x| *x > 0)", + ] { + let good = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&good), [], "{condition}"); + let bad = format!("#[test]\nfn t() {{\n assert!(({condition}) && ys.iter().all(|y| *y > 0));\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "a positive operand beside {condition}"); + } + } + + #[test] + fn all_reports_positive_boolean_operands() { + for condition in [ + "xs.iter().all(|x| *x > 0)", + "ready() && xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) && ready()", + "ready() || xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) || ready()", + "!!xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) == false", + "!(xs.iter().all(|x| *x > 0) == false)", + ] { + let bad = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{condition}"); + let good = bad.replace(" assert!", " assert_eq!(xs.len(), 3);\n assert!"); + assert_eq!(hits(&good), [], "a length check guards {condition}"); + } + } + + #[test] + fn all_guards_use_assertion_operands_and_skip_messages() { + for name in ["assert", "debug_assert", "prop_assert"] { + let good = format!("#[test]\nfn t() {{\n {name}!(xs.len() > 0);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} condition"); + let bad = format!("#[test]\nfn t() {{\n {name}!(ready(), \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (left, right) in [("xs.len()", "3"), ("3", "xs.len()")] { + let good = format!("#[test]\nfn t() {{\n {name}!({left}, {right});\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} operands"); + } + let bad = format!("#[test]\nfn t() {{\n {name}!(a, b, \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + } + + #[test] + fn all_guards_require_checks_of_collection_properties() { + for expr in ["xs.len()", "xs.is_empty()", "xs.iter().count()", "xs.first()", "xs.iter().any(|x| *x > 0)", "xs.iter().next()", "xs.last()"] { + let bad = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "unused {expr}"); + let good = format!("#[test]\nfn t() {{\n assert_eq!({expr}, expected);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "checked {expr}"); + } + } + + #[test] + fn all_guards_accept_first_item_access_that_fails_when_empty() { + for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] + { + let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{expr} fails when empty"); + let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "{expr} inside the predicate"); + let message = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0), \"item {{:?}}\", {expr});\n}}\n"); + assert_eq!(hits(&message), [(3, "all-unguarded")], "{expr} inside the message"); + } + let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + } + + #[test] + fn all_guards_accept_panicking_first_item_bindings() { + let good = "#[test]\nfn t() {\n let Some(x) = xs.first() else { panic!(\"empty\") };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let bad = "#[test]\nfn t() {\n let Some(x) = xs.first() else { skip(); };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + } + + #[test] + fn all_hits_count_changes_anywhere_in_their_test() { + let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].line, 5); + let guarded = src.replace(" assert!(xs.iter()", " assert!(!xs.is_empty());\n assert!(xs.iter()"); + assert_eq!(hits(&guarded), [], "the guard prevents the finding before deletion"); + for line in [1, 2, 3, 4, 5, 6] { + assert!(touches(&found[0], Some(&[line].into_iter().collect())), "test line {line}"); + } + assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); + let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; + let changed = parse_diff(diff); + assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); + } + + #[test] + fn all_allow_comments_stay_near_the_finding() { + let distant = "#[test]\nfn t() {\n // test-lint: allow all-unguarded empty input is allowed\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(distant), [(5, "all-unguarded")]); + let adjacent = "#[test]\nfn t() {\n let xs = f();\n // test-lint: allow all-unguarded empty input is allowed\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(adjacent), []); + let same = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| *x > 0)); // test-lint: allow all-unguarded empty input is allowed\n}\n"; + assert_eq!(hits(same), []); + } + + #[test] + fn only_weak_checks_are_reported_once_per_test() { + let bad = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert!(!list().is_empty());\n}\n"; + assert_eq!(hits(bad), [(2, "only-weak")]); + let good = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert_eq!(parse(\"a\").unwrap(), 1);\n}\n"; + assert_eq!(hits(good), []); + let refusal = "#[test]\nfn t() {\n assert!(parse(\"\").is_err());\n}\n"; + assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); + let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; + assert_eq!(hits(compound), []); + for cond in ["(parse(\"x\").is_ok())", "((parse(\"x\").is_ok()))", "!(list().is_empty())", "(!list().is_empty())"] { + let src = format!("#[test]\nfn t() {{\n assert!({cond});\n}}\n"); + assert_eq!(hits(&src), [(2, "only-weak")], "{cond}"); + } + let grouped = "#[test]\nfn t() {\n assert!((a.is_some()) && (a == Some(2)));\n}\n"; + assert_eq!(hits(grouped), [], "parentheses around one side of a comparison stay"); + } + + #[test] + fn functions_declared_in_a_test_count_only_when_called() { + let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; + assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; + assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); + let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &with_helpers), [], "a call to it checks"); + } + + #[test] + fn should_panic_counts_only_when_applied() { + let weak = "#[test]\nfn t() {\n assert!(parse(\"x\").is_ok());\n}\n"; + for attr in [ + "#[should_panic]", + "#[ should_panic(expected = \"x\") ]", + "#[cfg_attr(test, should_panic)]", + "#[cfg_attr( test , should_panic(expected = \"x\"))]", + ] { + assert_eq!(hits(&format!("{attr}\n{weak}")), [], "{attr}"); + } + for attr in ["#[cfg_attr(any(), should_panic)]", "#[cfg_attr(windows, should_panic)]", "#[doc = \"should_panic\"]", "#[allow(should_panic)]"] + { + assert_eq!(hits(&format!("{attr}\n{weak}")), [(3, "only-weak")], "{attr}"); + } + } + + #[test] + fn self_compare_needs_the_same_plain_expression() { + let bad = "#[test]\nfn t() {\n let x = f();\n assert_eq!(x.len(), x.len());\n assert_eq!(&x, x);\n}\n"; + assert_eq!(hits(bad), [(4, "self-compare"), (5, "self-compare")]); + let good = "#[test]\nfn t() {\n assert_eq!(write(&doc), write(&doc), \"deterministic\");\n assert_eq!(f(\"a\"), f(\"b\"));\n assert_ne!(\"a b\", \"ab\");\n assert_ne!(x /* one */, x.y);\n assert_ne!(' ', ':');\n}\n"; + assert_eq!(hits(good), [], "literal text, including its spaces, is compared"); + } + + #[test] + fn self_compare_counts_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n actual,\n actual,\n \"comparison\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!(hit.rule, Rule::SelfCompare); + assert_eq!((hit.line, hit.first, hit.last), (3, 3, 5)); + for line in [3, 4, 5] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [2, 6, 7] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + assert_eq!(hits(&src.replacen(" actual,", " expected,", 1)), []); + } + + #[test] + fn self_compare_keeps_exemptions_near_the_macro_opening() { + let src = "#[test]\nfn t() {\n assert_eq!( // MARKER\n actual, // OPERAND\n actual\n );\n}\n"; + let allow = "test-lint: allow self-compare checks the lint"; + assert_eq!(hits(&src.replace("MARKER", allow)), []); + assert_eq!(hits(&src.replace(" assert_eq!", &format!(" // {allow}\n assert_eq!"))), []); + assert_eq!(hits(&src.replace("OPERAND", allow)), [(3, "self-compare")]); + } + + #[test] + fn a_process_test_must_read_its_output() { + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).arg(\"x\").output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = "#[test]\nfn t() {\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success());\n assert_eq!(out.stdout, b\"ok\\n\");\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn process_status_checks_accept_every_comparison_assertion() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!(out.status.code(), Some(0), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name}"); + let good = bad.replace("Some(0)", "parse_code(&out.stdout)"); + assert_eq!(hits(&good), [], "{name} reads output in its second operand"); + } + } + + #[test] + fn process_status_checks_accept_either_compared_operand() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (expected, status) in [("Some(0)", "out.status.code()"), ("true", "out.status.success()")] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!({expected}, {status}, \"{{:?}}\", out.stdout);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name} with {status} on the right"); + let good = bad.replace(expected, "parse_status(&out.stderr)"); + assert_eq!(hits(&good), [], "{name} reads output in its first operand"); + let message = bad.replace(status, "expected_status"); + assert_eq!(hits(&message), [], "{name} has no status check in its operands"); + } + } + } + + #[test] + fn process_output_in_failure_messages_does_not_count_as_reading() { + for assertion in ["assert!(out.status.success()", "debug_assert!(out.status.success()", "prop_assert!(out.status.success()"] { + let bad = + format!("#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}, \"{{:?}}\", out.stderr);\n}}\n"); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("out.status.success()", "out.status.success() && out.stdout == expected"); + assert_eq!(hits(&good), [], "output in the condition of {assertion}"); + } + for assertion in ["assert_eq", "assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}!(out.status.code(), f::<A, B>(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::<A, B>()", "from_slice(&out.stdout)"); + assert_eq!(hits(&good), [], "output in the second operand of {assertion}"); + } + } + + #[test] + fn stream_configuration_does_not_count_as_reading_output() { + for stream in ["stdout", "stderr", "stdin"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).{stream}(Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{stream} configuration"); + let good = bad.replace(" assert!", " let _ = out.stderr;\n assert!"); + assert_eq!(hits(&good), [], "reading a field after {stream} configuration"); + } + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).stdout (std::process::Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace("std::process::Stdio::piped()", "output.stdout"); + assert_eq!(hits(&good), [], "a field read in a builder argument counts"); + } + + #[test] + fn output_inspection_counts_outside_failure_messages() { + for read in [ + "out.stdout", + "out.stderr", + "String::from_utf8(out.stdout)", + "fs::read(path)", + "read_to_string(path)", + "from_slice(data)", + "from_str(text)", + "text.contains(needle)", + ] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success(), \"{{:?}}\", {read});\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{read} in a message"); + let good = bad.replace(" assert!", &format!(" let _ = {read};\n assert!")); + assert_eq!(hits(&good), [], "{read} outside a message"); + } + } + + #[test] + fn failure_messages_are_removed_for_every_standard_assertion() { + for name in [ + "assert", + "debug_assert", + "prop_assert", + "assert_eq", + "assert_ne", + "debug_assert_eq", + "debug_assert_ne", + "prop_assert_eq", + "prop_assert_ne", + ] { + let operands = if guard_arg_count(name) == 1 { "true" } else { "left, right" }; + let bad = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0));\n {name}!({operands}, \"{{:?}}\", xs[0]);\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{name} message"); + let good = bad.replace(" assert!", " let _ = xs[0];\n assert!"); + assert_eq!(hits(&good), [], "access outside the {name} message"); + } + } + + #[test] + fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { + for operand in ["f::<A, B>()", "f::<A, Vec<B, C>>()", "f :: <A, B>()"] { + let src = format!("{operand}, expected, message"); + let m = mask(&src); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); + assert_eq!(args, [operand, "expected", "message"], "{operand}"); + let comparison = format!("a < b, {operand} > c, message"); + let m = mask(&comparison); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); + assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); + } + } + + #[test] + fn a_test_needs_an_assertion_or_an_asserting_helper() { + let bad = "#[test]\nfn t() {\n let d = open(\"x\").unwrap();\n d.save();\n}\n"; + assert_eq!(hits(bad), [(2, "no-assertion")]); + let panics = "fn f() {}\n/// Panics.\n#[should_panic(expected = \"x\")]\n#[test]\nfn p() {\n f();\n}\n"; + assert_eq!(hits(panics), [], "#[should_panic] before #[test]"); + let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); + let ctx = Ctx { helpers, ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); + let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); + assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx::default()), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::<u8>()", "check_round_trip::<A, Vec<B>>(x)", "value.check::<T>()", "value.check :: <Vec<Vec<T>>> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::<u8>", "value.check::<T>", "round_trip::<u8>()", "value.round_trip::<T>()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn generic_crate_helpers_count_through_other_helpers() { + let defs = "fn same<T>(a: T, b: T) { assert_eq!(a, b); }\nfn twice<T>(a: T) { same::<T>(a, a); }\nfn idle<T>() {}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/helpers.rs".to_owned(), defs.to_owned())]); + assert!(helpers["crates/x"].contains("same")); + assert!(helpers["crates/x"].contains("twice")); + assert!(!helpers["crates/x"].contains("idle")); + let ctx = Ctx { helpers, ..Ctx::default() }; + for call in ["same::<u8>(a, b)", "twice::<Vec<Vec<u8>>>(x)"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); + assert_eq!(hits_in("crates/y/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{call} in another crate"); + } + for expression in ["idle::<u8>()", "same::<u8>", "value.same::<u8>()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn early_returns_on_values_are_reported_and_resource_skips_are_not() { + let bad = "#[test]\nfn t() {\n let Some(n) = find() else { return };\n assert_eq!(n, 2);\n}\n"; + assert_eq!(hits(bad), [(3, "early-return")]); + let fonts = "#[test]\nfn t() {\n let Some(face) = installed_family(\"Kufi\") else { return; };\n assert_eq!(face.n, 2);\n}\n"; + assert_eq!(hits(fonts), []); + let closure = "#[test]\nfn t() {\n let f = |x: u8| { if x == 0 { return; } g(x) };\n assert_eq!(f(1), ());\n}\n"; + assert_eq!(hits(closure), []); + let last = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n if g() { return; }\n}\n"; + assert_eq!(hits(last), []); + let value = "#[test]\nfn t() -> Result<(), String> {\n if f()? == 0 { return Ok(()); }\n assert_eq!(g(), 1);\n Ok(())\n}\n"; + assert_eq!(hits(value), [(3, "early-return")]); + let checked = "#[test]\nfn t() {\n for _ in 0..9 {\n if g() == 1 {\n assert_eq!(f(), 2);\n return;\n }\n }\n panic!(\"never stable\");\n}\n"; + assert_eq!(hits(checked), [], "a return after an assertion in its block"); + let said = "#[test]\nfn t() {\n if !link(\"a\") {\n eprintln!(\"skipped: no links here\");\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(said), [], "a return after a printed skip note"); + let commented = "#[test]\nfn t() {\n let Some(w) = width() else { return }; // no wide font here\n assert_eq!(w, 2);\n}\n"; + assert_eq!(hits(commented), [], "a return whose line says why"); + let quiet = "#[test]\nfn t() {\n if !link(\"a\") {\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(quiet), [(4, "early-return")]); + } + + #[test] + fn ignore_needs_a_reason() { + let bad = "#[test]\n#[ignore]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[ignore = \" \"]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "ignore-without-reason"), (6, "ignore-without-reason")]); + let good = "#[test]\n#[ignore = \"a benchmark: run with --ignored\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn ignore_accepts_non_empty_raw_string_reasons() { + for hashes in ["", "#", "##", "########"] { + for reason in ["requires an external service", " service ", r"service \ path"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [], "{literal}"); + } + for reason in ["", " ", "\t\n"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [(2, "ignore-without-reason")], "{literal}"); + } + } + } + + #[test] + fn env_gates_need_a_variable_ci_sets() { + let bad = "#[test]\nfn t() {\n let Ok(dir) = std::env::var(\"MY_SAMPLES\") else { return };\n assert_eq!(count(&dir), 3);\n}\n"; + assert_eq!(hits(bad), [(3, "env-gate-unset")]); + let ci = "#[test]\nfn t() {\n if std::env::var(\"SET_IN_CI\").is_ok() { assert_eq!(f(), 1); }\n assert_eq!(std::env::var(\"CARGO_PKG_NAME\").unwrap(), \"x\");\n}\n"; + assert_eq!(hits(ci), []); + let child = "const CHILD: &str = \"X_TEST_CHILD\";\n#[test]\nfn t() {\n if std::env::var_os(\"X_TEST_CHILD\").is_some() { assert_eq!(f(), 1); }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(child), []); + } + + #[test] + fn env_gates_ignore_commented_out_setters() { + for setter in ["cmd.env(\"MY_SAMPLES\", dir);", "std::env::set_var(\"MY_SAMPLES\", \"x\");", "const X: &str = \"MY_SAMPLES\";"] { + for comment in [format!("// {setter}"), format!("/* {setter} */"), format!("/* outer /* {setter} */ end */")] { + let src = + format!("{comment}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{comment}"); + } + } + } + + #[test] + fn env_gates_keep_code_setters_and_literal_contents() { + for setter in [ + "cmd . env ( \"MY_SAMPLES\", dir);", + "std::env::set_var ( \"MY_SAMPLES\", \"x\");", + "set_var(\"MY_SAMPLES\", \"x\");", + "use std::env::set_var; fn setup() { set_var(\"MY_SAMPLES\", \"x\"); }", + "cmd.set_var(\"MY_SAMPLES\", \"x\");", + "const X: &str = \"MY_SAMPLES\";", + "cmd.env(/* name */ \"MY_SAMPLES\", dir);", + ] { + let src = format!("{setter}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [], "{setter}"); + assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); + } + let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; + let masked = String::from_utf8(mask_parts(src, true, false)).unwrap(); + assert!(masked.contains("\"https://host/*path*/\"")); + assert!(masked.contains("r#\"// kept /* kept */\"#")); + assert!(masked.contains("let c = '/';")); + assert!(!masked.contains("removed")); + } + + #[test] + fn env_gates_require_setter_call_boundaries() { + for reader in [ + "read_env(\"MY_SAMPLES\");", + "cmd.read_env(\"MY_SAMPLES\");", + "env(\"MY_SAMPLES\", dir);", + "my_set_var(\"MY_SAMPLES\", \"x\");", + "std::env::my_set_var(\"MY_SAMPLES\", \"x\");", + "cmd.my_set_var(\"MY_SAMPLES\", \"x\");", + ] { + let src = format!("{reader}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{reader}"); + } + } + + #[test] + fn sleep_in_test_code_is_reported() { + let bad = "fn wait() {\n std::thread::sleep(Duration::from_millis(5));\n}\n#[test]\nfn t() {\n thread::sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "sleep"), (6, "sleep")]); + let good = "fn sleep(d: D) {}\n#[test]\nfn t() {\n run(\"$.sleep(250)\");\n clock.sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + let shipped = "pub fn wait() {\n std::thread::sleep(D);\n}\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", shipped, &ctx()), [], "code before #[cfg(test)] is not test code"); + assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); + let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for gate in ["all(test, windows)", "all( test , not(target_arch = \"wasm32\") )", "all(feature = \"x\", all(unix, test))"] { + let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); + } + for attr in ["#[ cfg(all(test, unix))]", "#[/* test-only */cfg(test)]", "# [cfg (test)]"] { + let gated = format!("{attr}\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{attr}"); + } + for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { + let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); + } + for test_file in [ + "crates/x/src/tests.rs", + "crates/x/src/tests_wheel.rs", + "crates/x/src/widget_tests.rs", + "crates/x/tests/it/a.rs", + "crates/testkit/src/lib.rs", + ] { + assert_eq!(hits_in(test_file, shipped, &ctx()), [(2, "sleep")], "{test_file}"); + } + } + + #[test] + fn reading_rust_source_is_reported_outside_the_audits() { + let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; + assert_eq!(hits(bad), [(3, "reads-source")]); + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); + let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; + assert_eq!(hits(data), []); + } + + #[test] + fn allow_comments_need_the_rule_and_a_reason() { + let src = "#[test]\nfn t() {\n // test-lint: allow sleep the file clock has a 2 ms step\n thread::sleep(D);\n thread::sleep(D); // test-lint: allow sleep same\n assert_eq!(f(), 1);\n thread::sleep(D); // test-lint: allow sleep\n thread::sleep(D); // test-lint: allow early-return wrong rule\n}\n// test-lint: allow no-assertion a smoke test of the panic-free reader\n#[test]\nfn u() {\n let _ = read(b\"junk\");\n}\n"; + assert_eq!(hits(src), [(7, "sleep"), (8, "sleep")], "an allow covers its own line and the next, and needs a reason"); + let strings = "#[test]\nfn t() {\n let s = \"test-lint: allow sleep in a string\"; thread::sleep(D);\n let r = r#\"test-lint: allow sleep raw\"#; thread::sleep(D);\n /* test-lint: allow sleep a block comment */ thread::sleep(D);\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(strings), [(3, "sleep"), (4, "sleep")], "a marker in a literal is not an exemption"); + } + + #[test] + fn comments_and_strings_are_not_code() { + let src = "#[test]\nfn t() {\n // assert!(x.iter().all(|y| y))\n let s = \"thread::sleep(d); #[ignore]\";\n let r = r#\"env::var(\"NOPE\")\"#;\n let c = '\"';\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(src), []); + } + + #[test] + fn tests_are_found_by_their_attributes() { + let src = "#[cfg(test)]\nmod tests {\n #[tokio::test]\n async fn a() {}\n #[test_case(1)]\n fn b(n: u8) {}\n proptest! {\n #[test]\n fn c(x in 0..9u8) {}\n }\n #[test]\n fn d() -> Result<(), String> { Ok(()) }\n fn not_a_test() {}\n}\n"; + let names: Vec<String> = tests_in(&mask(src)).into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["a", "b", "c", "d"]); + } + + #[test] + fn changed_lines_come_from_the_new_side_of_each_hunk() { + let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; + let got = parse_diff(diff); + assert_eq!(got.len(), 2); + assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); + assert_eq!(got["crates/x/src/n.rs"], None); + } + + #[test] + fn deleting_the_first_attribute_changes_the_remaining_test() { + let path = "crates/x/src/tests.rs"; + for (prefix, anchor) in [("", 0), ("fn before() {}\n", 1)] { + let src = format!("{prefix}#[test]\nfn t() {{}}\n#[test]\nfn other() {{}}\n"); + let before = src.replacen("#[test]", "#[should_panic]\n#[test]", 1); + assert!(lint_file(path, &before, &ctx()).iter().all(|h| h.test != "t"), "the attribute prevents the finding"); + let found = lint_file(path, &src, &ctx()); + assert_eq!(found.len(), 2); + let old = anchor + 1; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); + let changed = parse_diff(&diff); + let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; + assert_eq!(changed[path], Some(expected.into_iter().collect())); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert_eq!(found[0].test, "t"); + assert!(touches(&found[0], changed[path].as_ref()), "the deletion changes the remaining test"); + assert!(!touches(&found[1], changed[path].as_ref()), "the following test is unchanged"); + } + } + + #[test] + fn only_hits_on_changed_lines_count() { + let src = "#[test]\nfn old() {\n f();\n}\n#[test]\nfn new() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 2); + let changed: BTreeSet<usize> = [7].into_iter().collect(); + let counted: Vec<&str> = found.iter().filter(|h| touches(h, Some(&changed))).map(|h| h.test.as_str()).collect(); + assert_eq!(counted, ["new"]); + assert_eq!(found.iter().filter(|h| touches(h, None)).count(), 2); + assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); + } + + #[test] + fn only_failing_rules_fail_the_check() { + let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + let ios = "#[cfg(target_os = \"ios\")]\n#[test]\nfn ios() {\n assert_eq!(f(), 1);\n}\n"; + assert!(finish(&lint_file("crates/x/src/tests.rs", ios, &ctx()), 0, 1, "base").is_err(), "never-run fails the check"); + let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; + let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; + let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); + assert_eq!(finish(&hits_of(weak), 0, 1, "base"), Ok(()), "only-weak only reports"); + let all = hits_of(&format!("{weak}{unguarded}{skipped}")); + assert_eq!(all.len(), 3); + let Err(message) = finish(&all, 0, 1, "base") else { panic!("ignore-without-reason fails the check") }; + assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); + assert!(message.contains("[ignore-without-reason] `skipped`"), "{message}"); + assert!(!message.contains("[only-weak]") && !message.contains("[all-unguarded]"), "{message}"); + assert_eq!(finish(&[], 3, 1, "base"), Ok(())); + } + + #[test] + fn options_reject_unknown_and_repeated_arguments() { + assert_eq!(Options::parse(&[]), Ok(Options::default())); + assert_eq!(Options::parse(&["--base", "abc"]), Ok(Options { all: false, base: Some("abc".into()) })); + assert_eq!(Options::parse(&["--all"]), Ok(Options { all: true, base: None })); + for bad in [&["--base"][..], &["--base", "--all"], &["--all", "--all"], &["--fix"], &["--all", "--base", "x"]] { + assert!(Options::parse(bad).unwrap_err().starts_with("test-lint:"), "{bad:?}"); + } + } + + #[test] + fn workflow_variables_count_as_set() { + let names: Vec<String> = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED", "X"]); + assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); + } + + #[test] + fn workflow_mapping_keys_count_without_reads_or_comments() { + let assigned: Vec<String> = upper_words("env:\n MY_SAMPLES: fixtures\n - OTHER_SAMPLES: fixtures\n EMPTY_SAMPLES:\n").collect(); + assert_eq!(assigned, ["MY_SAMPLES", "OTHER_SAMPLES", "EMPTY_SAMPLES"]); + let reads = "# MY_SAMPLES: fixtures\nif: env.MY_SAMPLES != ''\nrun: echo $OTHER_SAMPLES ${EMPTY_SAMPLES}\nvalue: ${{ env.MY_SAMPLES }}\n"; + assert_eq!(upper_words(reads).collect::<Vec<_>>(), Vec::<String>::new()); + } + + #[test] + fn workflow_script_assignments_count_without_reads_or_comments() { + for assignment in [ + " MY_SAMPLES=value", + " export MY_SAMPLES=value", + " run: MY_SAMPLES=value cargo test", + " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", + " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " MY_SAMPLES=value # OTHER_SAMPLES=value", + " MY_SAMPLES=\"#value\"", + " MY_SAMPLES=", + " - MY_SAMPLES=value", + ] { + assert_eq!(upper_words(assignment).collect::<Vec<_>>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::<Vec<_>>(), Vec::<String>::new(), "{commented}"); + } + let reads = "env.MY_SAMPLES=value\n${{ env.MY_SAMPLES }}\n$MY_SAMPLES\n${MY_SAMPLES}\nMY_SAMPLES==value\n"; + assert_eq!(upper_words(reads).collect::<Vec<_>>(), Vec::<String>::new()); + } + + #[test] + fn workflow_mentions_do_not_suppress_unset_gates() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); + } + for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); + } + } + + #[test] + fn printed_workflow_assignments_do_not_count() { + for line in + ["run: echo \"MY_SAMPLES=fixtures\"", " echo MY_SAMPLES=fixtures", " printf 'MY_SAMPLES=x\\n'", " true && echo \"MY_SAMPLES=x\""] + { + assert_eq!(upper_words(line).collect::<Vec<_>>(), Vec::<String>::new(), "{line}"); + } + for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + assert_eq!(upper_words(line).collect::<Vec<_>>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn patch_labels_are_decoded_before_filtering() { + let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); + } + + #[test] + fn test_case_arguments_and_inner_attributes_do_not_hide_tests() { + let cases = "#[test_case(1; \"one\")]\n#[test_case(2; \"two\")]\nfn t(n: u8) {}\n"; + assert_eq!(hits(cases), [(3, "no-assertion")]); + let inner = "#![allow(dead_code)]\n\n#[should_panic]\n#[test]\nfn t() {\n f();\n}\n#[test]\nfn u() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", &inner.replace("#[should_panic]\n", ""), &ctx()); + assert_eq!(found.iter().map(|h| (h.first, h.last)).collect::<Vec<_>>(), [(3, 6), (7, 10)], "{found:?}"); + assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); + } + + #[test] + fn helpers_with_a_shared_name_count_only_when_each_asserts() { + let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ..Ctx::default() }), [(8, "no-assertion")]); + let both = src.replace("{ f(); }", "{ assert!(f()); }"); + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); + } + + #[test] + fn a_changed_collection_loses_its_equality_guard() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + for change in ["xs.clear();", "xs.retain(|x| *x > 5);", "xs = vec![];"] { + let changed = src.replace("\n assert!", &format!("\n {change}\n assert!")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change}"); + } + } + + #[test] + fn stream_redirection_to_any_target_is_configuration() { + let bad = "#[test]\nfn t() {\n let status = Command::new(bin()).stdout(file).stderr(log.try_clone().unwrap()).status().unwrap();\n assert!(status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace(" assert!", " assert_eq!(fs::read(path).unwrap(), b\"ok\");\n assert!"); + assert_eq!(hits(&good), []); + } + + #[test] + fn async_blocks_end_their_own_returns() { + let src = "#[test]\nfn t() {\n block_on(async { if missing() { return; } work().await; });\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("async {", "async move {")), []); + let own = "#[tokio::test]\nasync fn t() {\n if missing() { return; }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(own), [(3, "early-return")], "a return from the test's own body"); + } + + #[test] + fn env_setters_in_literals_do_not_count_and_spans_reach_the_name() { + let src = "#[test]\nfn t() {\n let _example = r#\"cmd.env(\"MY_SAMPLES\", dir)\"#;\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(4, "env-gate-unset")]); + let constant = "const X: &str = r#\"= \"MY_SAMPLES\";\"#;\n#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(constant), [(4, "env-gate-unset")]); + let multiline = "#[test]\nfn t() {\n let dir = std::env::var(\n \"MY_SAMPLES\",\n );\n assert_eq!(f(dir), 3);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", multiline, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::<Vec<_>>(), [(Rule::EnvGateUnset, 3, 3, 4)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone"); + } + + #[test] + fn sleep_in_a_condition_poll_or_a_spawned_release_is_not_reported() { + let polls = [ + "fn wait(r: &R, back_off: bool) {\n while !r.load(SeqCst) {\n if back_off {\n thread::sleep(D);\n }\n }\n}\n", + "fn wait(r: &R) {\n loop {\n match r.state() {\n S::Done => break,\n _ => {\n thread::sleep(D);\n }\n }\n }\n}\n", + "fn wait(s: &S) -> P {\n loop {\n let p = s.progress();\n if p.done || Instant::now() > until {\n return p;\n }\n thread::sleep(D);\n }\n}\n", + "fn wait(g: &G) {\n while !g.0.load(SeqCst) {\n std::thread::sleep(Duration::from_millis(1));\n }\n}\n", + "fn wait(t: &mut T) {\n while t.waiting() {\n thread::sleep(D);\n t.poll();\n }\n}\n", + "fn wait(s: &S) {\n while s.execute(\"a\", &json!({})).unwrap()[\"n\"] != 1 && Instant::now() < until {\n thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(Duration::from_secs(10));\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait(r: &R) {\n while { r.load(SeqCst) } {\n thread::sleep(D);\n }\n}\n", + "fn wait(r: &R) {\n m! { r }\n while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n", + "fn wait(r: &R) {\n 'outer: while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(move || -> () {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait() -> P {\n let p = loop {\n let p = progress();\n if p.done {\n break p;\n }\n std::thread::sleep(D);\n };\n p\n}\n", + "#[test]\nfn t() {\n ::std::thread::spawn(move || {\n std::thread::sleep(D);\n release();\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait() {\n while ScheduleDuration::new().pending {\n thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D));\n assert_eq!(f(), 1);\n}\n", + "use std::thread::{self, spawn};\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait() {\n while !ready({ let key = 1; key }) {\n thread::sleep(D);\n }\n}\n", + "fn wait(pending: bool) {\n while pending || { ready() } {\n thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n assert_eq!(f(), 1);\n}\n", + "use std::thread;\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "use std::{thread, time::Duration};\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(Duration::ZERO);\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait(q: &Q) {\n while q.len() < 3 {\n thread::sleep(D);\n }\n}\n", + "fn wait(q: &Q) {\n while 0 < { q.len() } {\n thread::sleep(D);\n }\n}\n", + "fn wait(q: &Q) {\n while 3 > { q.len() } {\n thread::sleep(D);\n }\n}\n", + ]; + for src in polls { + assert_eq!(hits(src), [], "{src}"); + } + let timed = [ + "fn wait() {\n for _ in 0..3 {\n if ready() {\n thread::sleep(D);\n }\n }\n}\n", + "fn start() -> JoinHandle<()> {\n return std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n", + "fn start() -> JoinHandle<()> {\n return ::std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n", + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n fn unused() {}\n thread::sleep(D);\n }\n}\n", + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::from_millis(50) {\n thread::sleep(Duration::from_millis(5));\n }\n}\n", + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed().as_millis() < 50 {\n thread::sleep(D);\n }\n}\n", + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::new(1, 0) {\n thread::sleep(D);\n }\n}\n", + "fn wait() {\n let mut n = 0;\n loop {\n thread::sleep(D);\n n += 1;\n if n == 3 {\n break;\n }\n }\n}\n", + "fn wait(g: &G) {\n if g.ready() {\n thread::sleep(D);\n }\n}\n", + "fn wait() {\n let t0 = Instant::now();\n loop {\n thread::sleep(D);\n println!(\"{:?}\", t0.elapsed());\n if t0.elapsed() > D {\n break;\n }\n }\n}\n", + "#[test]\nfn t() {\n let h = run(move || {\n thread::sleep(D);\n });\n assert_eq!(h, 1);\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(D);\n })\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n", + "#[test]\nfn t() {\n handles.push(std::thread::spawn(move || {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n", + "#[test]\nfn t() {\n let release = std::thread::spawn(move || {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n release.join().unwrap();\n}\n", + "fn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait(t0: Instant) {\n while t0.elapsed() < Duration::new(1, 0) {\n let new = t0.elapsed();\n thread::sleep(D);\n }\n}\n", + "fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(delay());\n n += 1;\n }\n}\n", + "fn wait(t0: Instant) {\n while t0.elapsed().checked_sub(Duration::ZERO).unwrap() < D {\n thread::sleep(D);\n }\n}\n", + "fn wait(t0: Instant) {\n while t0.elapsed() < D {\n let _ = stringify!(probe());\n std::thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n while !ready() {\n std::thread::spawn(|| std::thread::sleep(D)).join().unwrap();\n }\n assert_eq!(f(), 1);\n}\n", + "fn wait() -> u8 {\n let mut n = 0;\n let r = loop {\n n += 1;\n if n == 3 {\n break n;\n }\n thread::sleep(D);\n };\n r\n}\n", + "fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n += 1;\n }\n}\n", + "use std::thread::spawn as spawn_thread;\nfn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "mod thread {\n pub fn spawn(f: impl FnOnce()) {\n f();\n }\n}\n#[test]\nfn t() {\n thread::spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "#[test]\nfn t() {\n let h = std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n h.join().unwrap();\n}\n", + "fn wait(r: &R) {\n while !r.load(SeqCst) {\n let x = {\n thread::sleep(D);\n 1\n };\n }\n}\n", + "fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n = n + 1;\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(prepare(|| {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n", + "fn wait(t0: Instant) {\n while t0.elapsed() < D {\n println!(\"{}\", 1u8.to_string());\n thread::sleep(D);\n }\n}\n", + "use crate::thread::spawn;\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "use std::thread::{self as worker};\nmod thread {\n pub fn spawn(f: impl FnOnce()) {\n f();\n }\n}\n#[test]\nfn t() {\n thread::spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + ]; + for src in timed { + assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}"); + } + } + + #[test] + fn an_edit_to_the_loop_around_a_sleep_counts_as_a_change() { + let src = "fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(D);\n n += 1;\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::<Vec<_>>(), [(Rule::Sleep, 4)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the loop's condition"); + assert!(!touches(&found[0], Some(&[2].into_iter().collect())), "a change outside the loop"); + } + + #[test] + fn an_edit_that_joins_a_spawned_sleep_counts_as_a_change() { + let block = "#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(D);\n })\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n"; + let bare = + "#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D))\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n"; + for (src, line, join) in [(block, 4, 7), (bare, 3, 5)] { + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::<Vec<_>>(), [(Rule::Sleep, line)], "{src}"); + assert!(touches(&found[0], Some(&[join].into_iter().collect())), "a change to the join: {src}"); + assert!(!touches(&found[0], Some(&[join + 1].into_iter().collect())), "a change after the statement: {src}"); + } + } + + #[test] + fn sleep_needs_the_thread_function() { + let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n"; + assert_eq!(hits(local), []); + for import in ["use std::thread::sleep;", "use std::thread::{self, sleep};"] { + let src = format!("{import}\n#[test]\nfn t() {{\n sleep(D);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [(4, "sleep")], "{import}"); + } + for import in ["use std::thread::sleep as nap;", "use std::thread::sleep_ms;", "use std::thread::{sleep as nap};"] { + let src = format!("{import}\nfn sleep(_: u8) {{}}\n#[test]\nfn t() {{\n sleep(1);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [], "{import}"); + } + assert_eq!(hits("#[test]\nfn t() {\n std :: thread :: sleep(D);\n assert_eq!(f(), 1);\n}\n"), [(3, "sleep")]); + } + + #[test] + fn raw_include_str_paths_are_checked() { + for literal in ["r\"../lib.rs\"", "r#\"../lib.rs\"#", "r##\"../lib.rs\"##"] { + let src = format!("#[test]\nfn t() {{\n let src = include_str!({literal});\n assert_eq!(src.len(), 1);\n}}\n"); + assert_eq!(hits(&src), [(3, "reads-source")], "{literal}"); + assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); + assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); + } + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + } + + #[test] + fn single_letter_variables_set_in_ci_count() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(3, "env-gate-unset")]); + let ctx = Ctx { ci_env: upper_words("env:\n X: 1\n").collect(), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + } + + #[test] + fn tests_with_non_ascii_names_are_checked() { + let src = "#[test]\nfn échec() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::<Vec<_>>(), [(2, "échec")]); + } + + #[test] + fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { + let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bare), [(3, "sleep")]); + assert_eq!(hits(&bare.replace("sleep */", "sleep the clock has a 2 ms step */")), []); + } + + #[test] + fn bindings_out_of_scope_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs: Vec<u8> = vec![];\n {\n let xs = vec![1];\n use_it(&xs);\n }\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + let inside = "#[test]\nfn t() {\n let xs: Vec<u8> = vec![];\n {\n let xs = vec![1];\n assert!(xs.iter().all(|x| *x > 0));\n }\n use_it(&xs);\n}\n"; + assert_eq!(hits(inside), []); + } + + #[test] + fn constants_with_several_values_are_unknown() { + let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec<usize> = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + assert_eq!(hits(&src.replace("mod a { const START: usize = 0; }\n", "").replace("END: usize = 2", "END: usize = 4")), []); + } + + #[test] + fn a_count_stops_guarding_when_its_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + } + + #[test] + fn checks_in_failure_messages_do_not_end_only_weak() { + let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; + assert_eq!(hits(src), [(2, "only-weak")]); + assert_eq!(hits(&src.replace(" assert!", " let _ = probe().unwrap_err();\n assert!")), []); + } + + #[test] + fn advancing_calls_are_not_self_comparisons() { + for operand in ["it.next()", "q.pop_front()", "rx.recv()"] { + let src = format!("#[test]\nfn t() {{\n assert_ne!({operand}, {operand});\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + } + assert_eq!(hits("#[test]\nfn t() {\n assert_eq!(x.len(), x.len());\n}\n"), [(3, "self-compare")]); + } + + #[test] + fn ignore_spans_reach_a_reason_on_the_next_line() { + let src = "#[test]\n#[ignore =\n \"\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::<Vec<_>>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); + } + + fn only(rule: &'static str, src: &str) -> Vec<(usize, &'static str)> { + hits(src).into_iter().filter(|h| h.1 == rule).collect() + } + + #[test] + fn mirrors_call_the_same_function_on_both_sides() { + let bad = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", bad), [(3, "mirror")]); + let written = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), Point::new(2.0, 4.0));\n}\n"; + assert_eq!(only("mirror", written), []); + let builders = "#[test]\nfn t() {\n assert_eq!(Some(area(a)), Some(4.0));\n assert_eq!(a.to_string(), b.to_string());\n}\n"; + assert_eq!(only("mirror", builders), [], "a builder or conversion on both sides"); + let same = "#[test]\nfn t() {\n assert_eq!(scale(p), scale(p));\n}\n"; + assert_eq!(only("mirror", same), [], "identical sides are self-compare's"); + let oracle = "#[test]\nfn t() {\n assert_eq!(actual::area(s), reference::area(s) * 2.0);\n}\n"; + assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths"); + let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; + assert_eq!(only("mirror", ne), [], "two inputs that must differ"); + let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); + let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; + assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + let swapped = "#[test]\nfn t() {\n assert_eq!(scale(p, 1.0) * 2.0, scale(p, 2.0));\n}\n"; + assert_eq!(only("mirror", swapped), [(3, "mirror")], "the arithmetic on the left side"); + } + + #[test] + fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { + let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; + assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", raw), [], "raw string keys"); + let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; + assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let raw_quote = "#[test]\nfn t() {\n assert_eq!(at(r#\"A\" B\"#), at(r#\"A\"B\"#) + 1);\n}\n"; + assert_eq!(only("mirror", raw_quote), [], "a quote inside a raw key does not end it"); + let computed = "#[test]\nfn t() {\n assert_eq!(label(\"A\".to_owned() + \"B\"), label(\"C\") + 1);\n}\n"; + assert_eq!(only("mirror", computed), [(3, "mirror")], "a computed string is not an entry key"); + let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; + assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); + let offset = + "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; + assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); + let period = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * v);\n}\n"; + assert_eq!(only("mirror", period), [], "the same arithmetic on both sides"); + let tails = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * w);\n}\n"; + assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); + } + + #[test] + fn echoes_check_only_constants_or_the_fixture() { + let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n"; + assert_eq!(only("constant-echo", constant), [(2, "constant-echo")]); + let fixture = + "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let n = 3;\n let _ = process(&input);\n assert_eq!(input.len(), n);\n}\n"; + assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); + let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n"); + let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n"); + let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); + let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; + assert_eq!(only("fixture-only", borrowed), [], "an immutable binding of a mutable reference"); + let pattern = "#[test]\nfn t() {\n let (a, b) = split(4);\n assert_eq!(a, 2);\n assert_eq!(b, 2);\n}\n"; + assert_eq!(only("fixture-only", pattern), [], "a pattern binding of a result"); + let mixed = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert_eq!(zoom_in(1.0), 2.0);\n}\n"; + assert_eq!(only("constant-echo", mixed), [], "one real assertion keeps the test"); + let shadowed = "#[test]\nfn t() {\n let x = 1;\n let x = double(x);\n assert_eq!(x, 2);\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "the reaching binding is a call"); + let helper = "#[test]\nfn t() {\n assert_eq!(MAX, 4);\n check_all();\n}\n"; + assert_eq!(only("constant-echo", helper), [], "an asserting helper"); + let printed = "#[test]\nfn t() {\n let got = sample(1.0);\n assert_eq!(format!(\"{got:?}\"), \"1\");\n}\n"; + assert_eq!(hits(printed), [], "format! reads a local inside its string"); + let scoped = "#[test]\nfn t() {\n let result = compute();\n {\n let result = 0;\n consume(result);\n }\n assert_eq!(result, 1);\n}\n"; + assert_eq!(hits(scoped), [], "a binding in a block that has ended"); + let later = "#[test]\nfn t() {\n let x = compute();\n let y = x;\n let x = 0;\n assert_eq!(y, 2);\n assert_eq!(x, 0);\n}\n"; + assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); + let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); + let struct_pattern = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", struct_pattern), [], "the braces of a struct pattern are not the body"); + let else_branch = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n consume(n);\n } else {\n assert_eq!(n, 0);\n }\n}\n"; + assert_eq!(only("fixture-only", else_branch), [(2, "fixture-only")], "the `else` branch sees the outer binding"); + let mut_pattern = + "#[test]\nfn t() {\n let n = 0;\n if let Some(mut n) = compute() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`"); + } + + #[test] + fn never_run_accepts_trailing_commas_in_cfg_predicates() { + for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [(3, "never-run")], "{pred}"); + } + for pred in ["all(unix,)", "any(unix,)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [], "{pred}"); + } + } + + #[test] + fn never_run_tests_are_compiled_out_on_every_ci_target() { + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", mac), [(3, "never-run")]); + let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1); + let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", file), [(3, "never-run")]); + let unix = "#[cfg(unix)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unix), [], "Linux runs it"); + let not_mac = "#[cfg(not(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", not_mac), []); + let raw = "#[cfg(target_os = r\"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", raw), [], "a raw string value"); + let feature = "#[cfg(feature = \"gpu\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", feature), [], "a feature CI may enable"); + let any = "#[cfg(any(target_os = \"macos\", target_os = \"linux\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", any), []); + let win = "#[cfg(windows)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("apps/vectorcraft/src/printing/tests.rs", win, &ctx()), [], "the printing workflow runs it on Windows"); + assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); + let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", other), [], "a cfg on another item"); + } + + #[test] + fn never_run_lists_tests_that_build_on_macos_or_windows_without_failing() { + let test = |gate: &str| format!("#[cfg({gate})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + let check = |path: &str, gate: &str| { + let found = lint_file(path, &test(gate), &ctx()); + assert_eq!(found.iter().filter(|h| h.rule == Rule::NeverRun).count(), 1, "{gate} is listed"); + finish(&found, 0, 1, "base") + }; + // A touchpad gesture test that egui can only drive on macOS. + assert!(check("crates/ui-egui/src/tests/quickpenwheel.rs", "target_os = \"macos\"").is_ok(), "macOS"); + // A test of performance counters that only Windows has. + assert!(check("apps/vectorcraft-cli/src/perf.rs", "windows").is_ok(), "Windows"); + assert!(check("crates/x/src/tests.rs", "all(target_os = \"macos\", target_arch = \"aarch64\")").is_ok(), "Apple silicon"); + assert!(check("crates/x/src/tests.rs", "target_os = \"ios\"").is_err(), "no desktop target builds it"); + assert!(check("crates/x/src/tests.rs", "all(windows, unix)").is_err(), "no target builds it"); + let found = lint_file("apps/vectorcraft-cli/src/perf.rs", &test("windows"), &ctx()); + assert!(found[0].note.ends_with("it builds on Windows, so run it there"), "{}", found[0].note); + } + + #[test] + fn module_gates_reads_each_candidate_once() { + let paths: Vec<String> = (0..32).map(|i| format!("crates/x/src/parent/child{i}.rs")).collect(); + let parent = (0..32).map(|i| format!("mod child{i};\n")).collect::<String>(); + let files = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n"), ("crates/x/src/parent.rs", parent.as_str())]; + let reads = RefCell::new(HashMap::<String, usize>::new()); + let read = |p: &str| { + *reads.borrow_mut().entry(p.to_owned()).or_default() += 1; + files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()) + }; + let gates = module_gates(&paths, &read, &Overrides::new()); + assert_eq!(gates.len(), paths.len(), "every child inherits the parent gate"); + let reads = reads.borrow(); + assert_eq!(reads.get("crates/x/src/lib.rs"), Some(&1), "a shared ancestor"); + assert_eq!(reads.get("crates/x/src/parent.rs"), Some(&1), "a shared parent"); + assert_eq!(reads.get("crates/x/src/parent/mod.rs"), Some(&1), "a missing candidate"); + for (path, count) in reads.iter() { + assert_eq!(*count, 1, "candidate {path}"); + } + } + + #[test] + fn never_run_follows_the_cfg_of_the_mod_declaration() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod mac;\nmod plain;\n"), + ("crates/x/src/mac.rs", "mod inner;\n"), + ("crates/x/src/mac/inner.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec<String> = ["crates/x/src/mac.rs", "crates/x/src/mac/inner.rs", "crates/x/src/plain.rs", "crates/x/tests/it.rs"] + .into_iter() + .map(String::from) + .collect(); + let cfgs = module_cfgs(&paths, &read, &Overrides::new()); + assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..])); + assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs"); + assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs")); + let ctx = Ctx { module_cfgs: cfgs, ..ctx() }; + let test = "#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/mac/inner.rs", test, &ctx), [(4, "never-run")]); + assert_eq!(hits_in("crates/x/src/plain.rs", test, &ctx), []); + } + + #[test] + fn never_run_follows_the_cfg_around_the_mod_declaration() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p); + let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; + assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); + let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; + assert_eq!(declared(block, &child), None, "that `mod child;` loads platform/child.rs"); + let platform = ["platform".to_owned()]; + let nested = Loaded { path: "src/platform/child.rs", name: "child", chain: &platform }; + assert_eq!(declared(block, &nested), Some(vec!["windows".to_owned()]), "the gate on the inline module"); + let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n"; + assert_eq!(declared(both, &child), Some(vec![]), "the root declaration, not the one in platform"); + let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n"; + assert_eq!(declared(gated, &child), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); + assert_eq!(declared("mod child;\n", &child), Some(vec![])); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\nmod child;\n"; + assert_eq!(declared(commented, &child), Some(vec!["target_os=\"linux\"".to_owned()]), "a comment in the predicate"); + let paths = "#[cfg(windows)]\n#[path = \"windows.rs\"]\nmod imp;\n#[cfg(not(windows))]\nmod imp;\n"; + let imp = Loaded { path: "src/imp.rs", name: "imp", chain: &[] }; + assert_eq!(declared(paths, &imp), Some(vec!["not(windows)".to_owned()]), "the declaration that loads imp.rs"); + let win = Loaded { path: "src/windows.rs", name: "windows", chain: &[] }; + assert_eq!(declared(paths, &win), Some(vec!["windows".to_owned()]), "the `#[path]` override"); + let twice = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(target_os = \"linux\")]\n#[path = \"child.rs\"]\nmod other;\n"; + assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()])); + let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n"; + assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()])); + } + + #[test] + fn never_run_reads_cfg_attr_and_commented_predicates() { + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "Linux runs it"); + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", mac), [(3, "never-run")]); + let nested = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")], "unix holds on every CI target, so the nested cfg applies"); + let unknown = "#[cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), [], "a condition that may not hold"); + } + + #[test] + fn a_changed_parent_declaration_counts_for_the_child_tests() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "mod plain;\n#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); + let lib = |lines: &[usize]| -> BTreeMap<String, Option<BTreeSet<usize>>> { + [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() + }; + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multiline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod child;\nmod plain;\n"), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| multiline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "a line inside a multiline predicate"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[6])), "another declaration"); + let enclosing: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod platform {\n mod child;\n}\nmod plain;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| enclosing.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[3])), "a line inside the inline module's predicate"); + assert!(!gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[8])), "a declaration outside the inline module"); + } + + #[test] + fn never_run_follows_a_path_override_in_a_sibling_file() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod solids;\n"), + ("crates/x/src/solids/mod.rs", "mod graphics;\n"), + ("crates/x/src/solids/graphics.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"tests_graphics.rs\"]\nmod tests;\n"), + ("crates/x/src/solids/tests_graphics.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/solids/tests_graphics.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&child), &read, &overrides); + assert_eq!(gates.get(&child).map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let changed: BTreeMap<String, Option<BTreeSet<usize>>> = + [("crates/x/src/solids/graphics.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(&child), &changed), "a cfg added to the sibling's declaration"); + } + + #[test] + fn never_run_keeps_crate_roots_independent_of_path_overrides() { + for child in [ + "crates/x/tests/shared.rs", + "crates/x/src/lib.rs", + "crates/x/src/main.rs", + "crates/x/src/bin/tool.rs", + "crates/x/examples/demo.rs", + "crates/x/benches/speed.rs", + "crates/x/build.rs", + ] { + let declaration = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod shared;\n", child.strip_prefix("crates/x/").unwrap()); + let files = [("crates/x/other.rs", declaration.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the crate root runs independently: {child}"); + let gated = format!("#[cfg(target_os = \"macos\")]\n{test}"); + assert_eq!(hits_in(child, &gated, &ctx), [(3, "never-run")], "the root's own cfg still applies: {child}"); + } + } + + #[test] + fn a_namesake_already_off_does_not_hide_a_newly_off_test() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let path = "crates/x/src/child.rs"; + let base = lint_file(path, src, &ctx()); + let now = + lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect(); + assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); + } + + #[test] + fn a_test_off_at_the_base_is_matched_in_the_base_source() { + // At the base an inline module gate turned the test off; the change removes that gate and + // gates the parent instead, which also moves the test up a line. + let path = "crates/x/src/child.rs"; + let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<&str> = + now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); + } + + #[test] + fn a_removed_namesake_module_does_not_hide_a_newly_off_test() { + // `a::t` was off at the base and `b::t` ran; the change deletes `mod a` and gates the parent, + // so `b::t` is now the only `t` in the file. + let path = "crates/x/src/child.rs"; + let before = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.line).collect(); + assert_eq!(off, [3], "`b::t` is newly off"); + } + + #[test] + fn never_run_follows_a_tests_module_directory_under_src() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod tests;\n"), ("crates/x/src/tests.rs", "mod fonts;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/tests/fonts.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); + assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"), + ("crates/x/tests/smoke.rs", "mod common;\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec<String> = files.keys().map(|p| (*p).to_owned()).collect(); + let overrides = with_root_routes(path_overrides(files.iter().map(|(p, s)| (*p, *s))), &paths); + let shared = "crates/x/tests/common/mod.rs".to_owned(); + let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target"); + // Only a macOS-gated declaration in the target beside it loads the helper. + let gated: HashMap<&str, &str> = [ + ("crates/x/tests/smoke.rs", "#[cfg(target_os = \"macos\")]\nmod common;\n"), + ("crates/x/tests/other.rs", "fn main() {}\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| gated.get(p).map(|s| (*s).to_owned()); + let paths: Vec<String> = gated.keys().map(|p| (*p).to_owned()).collect(); + let overrides = with_root_routes(Overrides::new(), &paths); + let gated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &gated_ctx), [(2, "never-run")], "the only target that loads it is macOS-only"); + let child = "crates/x/tests/common/helpers.rs".to_owned(); + let with_child: HashMap<&str, &str> = + gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/common/mod.rs", "mod helpers;\n")]).collect(); + let read = |p: &str| with_child.get(p).map(|s| (*s).to_owned()); + let child_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&child, test, &child_ctx), [(2, "never-run")], "a module below the helper inherits the gate"); + let ungated: HashMap<&str, &str> = gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/other.rs", "mod common;\n")]).collect(); + let read = |p: &str| ungated.get(p).map(|s| (*s).to_owned()); + let ungated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &ungated_ctx), [], "another target loads it on every target"); + } + + #[test] + fn a_cfg_attr_path_on_an_inline_module_is_a_conditional_route() { + let lib = "#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\", path = \"generated\")]\nmod platform {\n mod child;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let generated = "crates/x/src/generated/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&generated, test, &ctx), [(2, "never-run")], "loaded only where the macOS override applies"); + let unix = lib.replace("#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\"", "#[cfg_attr(unix"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", unix.as_str())].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&generated, test, &ctx), [], "the override applies on Linux and FreeBSD"); + let default = "crates/x/src/platform/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&default), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&default, test, &ctx), [(2, "never-run")], "the default directory is used only on Windows"); + } + + #[test] + fn a_path_loaded_file_declares_its_modules_beside_it() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"impl/platform.rs\"]\nmod platform;\n"), + ("crates/x/src/impl/platform.rs", "mod child;\n"), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "impl/platform.rs loads impl/child.rs"); + let below = "crates/x/src/impl/platform/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&below), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs"); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec<String> = files.keys().map(|p| (*p).to_owned()).collect(); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child), + "a change to platform.rs reaches child.rs" + ); + } + + #[test] + fn a_named_route_takes_only_the_gates_of_named_declarations() { + // `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route + // loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`. + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"), + ("crates/x/src/parent.rs", "mod child;\n"), + ("crates/x/src/parent/child.rs", ""), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] { + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(child, test, &ctx), expected, "{child}"); + } + } + + #[test] + fn a_removed_child_declaration_still_reaches_the_child() { + let work: HashMap<&str, &str> = [ + ( + "crates/x/src/lib.rs", + "#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n", + ), + ("crates/x/src/impl/platform.rs", ""), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| work.get(p).map(|s| (*s).to_owned()); + let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) }; + let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s))); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec<String> = work.keys().map(|p| (*p).to_owned()).collect(); + let child = "crates/x/src/impl/child.rs".to_owned(); + assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child)); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child), + "the base `mod child;` that the change removed still leads to child.rs" + ); + } + + #[test] + fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let files = [ + ("crates/x/src/a.rs", "#[cfg(target_os = \"macos\")]\n#[ path = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[\npath = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/decoy.rs", "// path is not a module attribute\nmod other;\n"), + ]; + for (path, src) in files { + std::fs::write(root.join(path), src).unwrap(); + } + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + for revision in [None, Some(base.as_str())] { + let read = |p: &str| match revision { + Some(base) => git(&root, &["show", &format!("{base}:{p}")]).ok(), + None => read_small(&root, p), + }; + let overrides = discover_path_overrides(&root, revision, &read); + let child = "crates/x/src/shared.rs"; + let parents: BTreeSet<&str> = overrides.get(child).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, [files[0].0, files[1].0].into_iter().collect(), "both whitespace forms: {revision:?}"); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}"); + } + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn base_root_routes_come_from_the_base_tree() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); + std::fs::write(root.join("crates/x/tests/common/mod.rs"), "").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::remove_file(root.join("crates/x/tests/smoke.rs")).unwrap(); + let shared = "crates/x/tests/common/mod.rs"; + let now = vec![shared.to_owned()]; + assert!(with_root_routes(Overrides::new(), &now).get(shared).is_none_or(|r| r.is_empty()), "no root loads it now"); + let then = base_files(&root, &base).unwrap(); + let routes = with_root_routes(Overrides::new(), &then); + let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn never_run_follows_a_path_selected_by_cfg_attr() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"), + ("crates/x/src/live.rs", ""), + ("crates/x/src/platform.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let live = "crates/x/src/live.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() }; + assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path"); + let platform = "crates/x/src/platform.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); + assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + } + + #[test] + fn changed_lines_lists_both_paths_of_an_exact_rename() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; + std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap(); + std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap(); + git(&root, &["add", "-A"]).unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); + assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn never_run_joins_inline_and_override_routes() { + for (lib, child) in [ + ("mod platform { mod child; }\nmod a;\n", "crates/x/src/platform/child.rs"), + ("mod platform { mod nested { mod child; } }\nmod a;\n", "crates/x/src/platform/nested/child.rs"), + ] { + let a = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod other;\n", child.strip_prefix("crates/x/src/").unwrap_or(child)); + let files = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", a.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the ungated inline route runs it"); + for parent in ["crates/x/src/lib.rs", "crates/x/src/a.rs"] { + let changed = [(parent.to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "both routes contribute their source lines: {parent}"); + } + } + } + + #[test] + fn never_run_keeps_default_and_override_files_separate() { + let files = [ + ("crates/x/src/lib.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod other;\n"), + ]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let paths = ["crates/x/src/shared.rs".to_owned(), "crates/x/src/a/shared.rs".to_owned()]; + let gates = module_gates(&paths, &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&paths[0], test, &ctx), [(2, "never-run")], "only the macOS override loads this file"); + assert_eq!(hits_in(&paths[1], test, &ctx), [], "the default declaration loads the file under a/"); + let changed = [("crates/x/src/a.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(!gate_changed(gates.get(&paths[0]), &changed), "the default declaration belongs to the other file"); + } + + #[test] + fn never_run_resolves_every_routes_ancestors() { + for (a, b, child) in [ + ("#[path = \"shared.rs\"]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n", "crates/x/src/shared.rs"), + ("mod shared;\n", "#[path = \"a/shared.rs\"]\nmod s;\n", "crates/x/src/a/shared.rs"), + ] { + for target in ["linux", "macos"] { + let lib = format!("#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"{target}\")]\nmod b;\n"); + let files = [("crates/x/src/lib.rs", lib.as_str()), ("crates/x/src/a.rs", a), ("crates/x/src/b.rs", b)]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let expected = if target == "linux" { vec![] } else { vec![(2, "never-run")] }; + assert_eq!(hits_in(child, test, &ctx), expected, "the second route's ancestors decide whether Linux runs it"); + for (parent, line) in [ + ("crates/x/src/a.rs", if a.starts_with("#[path") { 2 } else { 1 }), + ("crates/x/src/b.rs", 2), + ("crates/x/src/lib.rs", 2), + ("crates/x/src/lib.rs", 4), + ] { + let changed = [(parent.to_owned(), Some([line].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "every route and its ancestors: {parent}:{line}"); + } + } + } + } + + #[test] + fn removed_module_routes_count_only_newly_off_tests() { + let a = "crates/x/src/a.rs"; + let child = "crates/x/src/shared.rs"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let mac = "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"; + let work_files = [("crates/x/src/lib.rs", "mod a;\nmod b;\n"), (a, ""), ("crates/x/src/b.rs", mac)]; + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(work_files); + let paths = [child.to_owned()]; + let gates = module_gates(&paths, &read_work, &overrides); + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let hit = lint_file(child, test, &work_ctx).into_iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + for (before, ran) in [(declaration, true), (mac, false)] { + let base_files = [("crates/x/src/lib.rs", work_files[0].1), (a, before), ("crates/x/src/b.rs", mac)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = path_overrides(base_files); + let base_gates = module_gates(&paths, &read_base, &base_overrides); + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::<Vec<_>>(); + assert!( + descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()), + "the removed route still reaches the shared tests" + ); + for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { + let changed = [(a.to_owned(), lines)].into_iter().collect(); + assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); + let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); + assert!(parent_changed, "deletions and shifted lines still change a base route"); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran); + assert!( + route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), + "a base route parent counts even without inherited predicates" + ); + } + let changed = [("crates/x/src/lib.rs".to_owned(), Some([20].into_iter().collect()))].into_iter().collect(); + assert!( + route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed), + "an edited base ancestor counts even when its old line numbers do not match" + ); + } + } + + #[test] + fn base_path_overrides_follow_declarations_before_a_move() { + let a = "crates/x/src/a.rs"; + let b = "crates/x/src/b.rs"; + let child = "crates/x/src/shared.rs"; + let lib = "#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let base_files = [("crates/x/src/lib.rs", lib), (a, declaration), (b, "")]; + let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = listed_path_overrides(&format!("before:{a}\0"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\0"), None, &read_work); + let paths = [child.to_owned()]; + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &work_ctx), [(2, "never-run")]); + assert_eq!(hits_in(child, test, &base_ctx), [(2, "never-run")], "the test was already off before the equally gated declaration moved"); + } + + #[test] + fn never_run_joins_two_inline_routes_from_one_file() { + let a = "#[cfg(target_os = \"macos\")]\nmod m {\n #[path = \"../shared.rs\"]\n mod s;\n}\nmod n {\n #[path = \"../shared.rs\"]\n mod s;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", a)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/a/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); + } + + #[test] + fn a_detached_module_is_not_an_ungated_route() { + let decl = "#[path = \"shared.rs\"]\nmod s;\n"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let shared = "crates/x/src/shared.rs".to_owned(); + for (lib, off) in [("#[cfg(target_os = \"macos\")]\nmod b;\n", true), ("mod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n", false)] { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", decl), ("crates/x/src/b.rs", decl)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let want: &[(usize, &str)] = if off { &[(2, "never-run")] } else { &[] }; + assert_eq!(hits_in(&shared, test, &ctx), want, "{lib}"); + } + } + + #[test] + fn a_path_on_an_inline_module_sets_its_directory() { + let lib = "#[cfg(target_os = \"macos\")]\n#[path = \"platform_impl\"]\nmod platform {\n mod child;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/platform_impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]); + } + + #[test] + fn cfg_values_compare_decoded_strings() { + let linux = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"\\x6cinux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true)); + assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value"); + } + + #[test] + fn path_override_listings_are_nul_separated() { + let files: HashMap<&str, &str> = + [("crates/x/src/a.rs", "#[path = \"s.rs\"]\nmod s;\n"), ("crates/x/src/caf\u{e9}.rs", "#[path = \"t.rs\"]\nmod t;\n")] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let got = listed_path_overrides("base:crates/x/src/a.rs\0base:crates/x/src/caf\u{e9}.rs\0", Some("base"), &read); + assert!(got.contains_key("crates/x/src/s.rs"), "{got:?}"); + assert!(got.contains_key("crates/x/src/t.rs"), "{got:?}"); + } + + #[test] + fn deleted_files_are_kept_as_changed() { + let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); + let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); + let seeds: Vec<String> = got.keys().cloned().collect(); + let files = ["crates/x/src/shared.rs".to_owned()]; + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]); + } + + #[test] + fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { + let files: Vec<String> = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] + .into_iter() + .map(String::from) + .collect(); + let sources = [ + ("src/solids/graphics.rs", "#[path = \"map_art.rs\"]\nmod art;\n"), + ("src/solids/map_art.rs", "#[path = \"tests_map_art.rs\"]\nmod tests;\n"), + ]; + let overrides = path_overrides(sources); + let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None); + assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); + } + + #[test] + fn never_run_counts_every_line_of_a_multiline_test_gate() { + let src = + "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[3].into_iter().collect())), "an edit inside the predicate"); + } + + #[test] + fn never_run_skips_later_attributes_and_true_gates() { + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + let unix = "#[cfg(unix)]\nmod u {\n #[cfg(target_os = \"macos\")]\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", unix, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[1].into_iter().collect())), "cfg(unix) holds on Linux and FreeBSD"); + assert!(touches(hit, Some(&[3].into_iter().collect())), "the macOS-only cfg on the test"); + } + + #[test] + fn never_run_takes_every_declaration_of_a_module() { + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let both = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let windows = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; + assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); + } + + #[test] + fn never_run_hits_cover_the_attribute_that_turns_the_test_off() { + let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line, h.gates.clone())); + assert_eq!(hit, Some((3, 4, vec![1]))); + assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the module cfg and the test"); + let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n"; + let left: Vec<usize> = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect(); + assert_eq!(left, [9], "an allow above one test leaves the next one reported"); + } + + #[test] + fn exact_pixels_compare_a_rect_with_numbers() { + let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); + let px = |body: &str| only("exact-pixel", &ui(body)); + assert_eq!(px("assert_eq!(button_rect.min.x, 12.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert_eq!(resp.rect, Rect::from_min_size(pos2(0.0, 20.0), vec2(80.0, 24.0)));"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); + assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference"); + assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); + assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); + assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); + assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); + assert_eq!(px("assert_eq!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc"); + assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); + assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(count_items(button_rect), 3);"), [], "a rect passed to a call"); + assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed to a call"); + assert_eq!(px("assert_eq!((button_rect.width()), 120.0);"), [(4, "exact-pixel")], "grouping parentheses"); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); + let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; + assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); + } + + #[test] + fn reads_source_covers_read_to_string_of_rust_files() { + let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(3, "reads-source")]); + let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", data), []); + let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal"); + let joined = + "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); + let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument"); + let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", extension), [], "a final extension that is not rs"); + let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", to_rs), [(3, "reads-source")], "a final extension of rs"); + let ext_var = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(ext)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", ext_var), [], "a final extension that is not a literal"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); + let format_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); + let grouped_ext = "#[test]\nfn t() {\n let s = fs::read_to_string((root.join(\"sample.rs\").with_extension(ext))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_ext), [], "grouping around the argument hides no step"); + let grouped_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(&(root.join(\"src/lib.rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_rs), [(3, "reads-source")], "a grouped join that names a .rs file"); + let computed = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\".trim_end_matches(\".rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", computed), [], "a computed file name is not its last literal"); + let wrapped = "#[test]\nfn t() {\n let s = fs::read_to_string(Path::new(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", wrapped), [(3, "reads-source")], "a literal inside Path::new"); + let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found = lint_file("crates/x/src/tests.rs", split, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); + assert_eq!((hit.line, hit.last), (3, 5), "the span runs through the path on the next line"); + assert!(touches(hit, Some(&[4].into_iter().collect()))); + } + + #[test] + fn weak_predicates_keep_the_polarity_of_a_negation() { + assert!(weak_predicate("parse(input).is_ok()")); + assert!(weak_predicate("!xs.is_empty()")); + assert!(!weak_predicate("!parse(input).is_ok()"), "a rejection"); + assert!(!weak_predicate("!x.is_some()"), "an absence"); + assert!(weak_predicate("!!x.is_some()")); + } + + #[test] + fn negated_membership_checks_are_not_presence_checks() { + assert!(!weak_predicate("!errors_for(c).contains(&Error::Unexpected)")); + assert!(!weak_predicate("!map.contains_key(&k)")); + assert!(weak_predicate("!items.is_empty()")); + assert!(weak_predicate("errors_for(c).contains(&Error::Expected)")); + } + + #[test] + fn a_for_binding_shadows_the_outer_one_in_its_body() { + let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", looped), []); + let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); + let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mutable), [], "`mut n` binds `n`"); + let destructured = "#[test]\nfn t() {\n let n = 0;\n for Row { n } in rows() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", destructured), [], "the braces of a struct pattern are not the loop body"); + let mut_after = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", mut_after), [(2, "fixture-only")], "the outer binding after a `mut` loop"); + } + + #[test] + fn a_closure_parameter_shadows_the_outer_binding_in_its_body() { + let closure = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| assert_eq!(n, 1));\n}\n"; + assert_eq!(only("fixture-only", closure), []); + let block = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(move |n| {\n assert_eq!(n, 1);\n });\n}\n"; + assert_eq!(only("fixture-only", block), [], "a block body"); + let captured = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|m| assert_eq!(n, 0));\n}\n"; + assert_eq!(only("fixture-only", captured), [(2, "fixture-only")], "an unshadowed name is the captured fixture"); + } + + #[test] + fn nested_cfg_attr_gates_apply() { + let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")]); + let unknown = "#[cfg_attr(unix, cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), []); + let bracket = "#[cfg(any(target_os = \"(\", unix))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", bracket), [], "a bracket inside a string value"); + let comma = "#[cfg_attr(target_os = \",\", cfg(windows))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", comma), [], "a comma inside the condition's value"); + let src = "#[cfg_attr(unix, path = \"a,b.rs\")]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + } + + #[test] + fn path_attributes_accept_raw_strings() { + for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] { + assert_eq!(path_attr(&mask(src), src.as_bytes(), 0, src.len()).as_deref(), Some("shared.rs"), "{src}"); + } + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod a;\nmod b;\n"), + ("crates/x/src/a.rs", "#[path = r\"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); + } + + #[test] + fn a_module_loaded_by_two_roots_runs_if_either_runs_it() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ("crates/x/src/shared.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); + } +}