diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 6427f339db..55d2a1983c 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -123,7 +123,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", diff --git a/.github/scripts/release-rpm-smoke.py b/.github/scripts/release-rpm-smoke.py new file mode 100644 index 0000000000..3d70cca7c1 --- /dev/null +++ b/.github/scripts/release-rpm-smoke.py @@ -0,0 +1,74 @@ +"""Check a real installed release RPM and exercise the GUI control channel.""" + +import json +import os +from pathlib import Path +import secrets +import socket +import subprocess +import time +import tempfile + + +def run_smoke(results): + requirements = (results / "rpm-requires.txt").read_text() + for capability in ( + "libc.so.6()(64bit)", + "libm.so.6(GLIBC_2.35)(64bit)", + "libgcc_s.so.1()(64bit)", + "libxkbcommon.so.0()(64bit)", + "(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))", + ): + if capability not in requirements.splitlines(): + raise RuntimeError(f"Missing RPM requirement: {capability}") + + version = subprocess.check_output(["vectorcraft-cli", "--version"], text=True) + (results / "cli-version.txt").write_text(version) + # Original fixture authored for this package smoke test; no external artwork. + fixture = results / "original-smoke.svg" + fixture.write_text('' + '' + '') + token = secrets.token_hex(32) + with tempfile.TemporaryDirectory(prefix="vectorcraft-runtime-") as runtime, (results / "gui.log").open("w") as log: + env = dict(os.environ, VECTORCRAFT_NO_PREFS="1", XDG_RUNTIME_DIR=runtime, + VECTORCRAFT_CONTROL_TOKEN=token) + app = subprocess.Popen([ + "vectorcraft", "--control", "32180", "--automation-read-root", str(results), + "--automation-write-root", str(results), str(fixture), + ], stdout=log, stderr=subprocess.STDOUT, env=env) + try: + deadline = time.monotonic() + 90 + while True: + if app.poll() is not None: + raise RuntimeError(f"GUI exited during startup: {app.returncode}") + try: + channel = socket.create_connection(("127.0.0.1", 32180), timeout=5) + break + except OSError: + if time.monotonic() >= deadline: + raise RuntimeError("GUI control channel did not become ready") from None + time.sleep(1) + channel.settimeout(30) + with channel, channel.makefile("rwb") as stream: + for request_id, method, params in ( + (0, "auth", {"token": token}), + (1, "ui.inspect", {}), + ): + stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode()) + stream.flush() + response = json.loads(stream.readline()) + (results / f"{method}.json").write_text(json.dumps(response, indent=2)) + if response.get("id") != request_id or response.get("ok") is not True: + raise RuntimeError(f"GUI request failed: {method}") + finally: + app.terminate() + try: + app.wait(timeout=10) + except subprocess.TimeoutExpired: + app.kill() + app.wait() + + +if __name__ == "__main__": + run_smoke(Path("/results")) diff --git a/.github/scripts/tests/test_release_rpm_smoke.py b/.github/scripts/tests/test_release_rpm_smoke.py new file mode 100644 index 0000000000..9d92237534 --- /dev/null +++ b/.github/scripts/tests/test_release_rpm_smoke.py @@ -0,0 +1,116 @@ +"""Exercise failures that an installed-package happy-path check cannot reproduce.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import MagicMock, patch + +spec = importlib.util.spec_from_file_location("rpm_smoke", Path(__file__).parents[1] / "release-rpm-smoke.py") +smoke = importlib.util.module_from_spec(spec) +spec.loader.exec_module(smoke) + + +class SmokeLifecycleTests(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.results = Path(self.folder.name) + (self.results / "rpm-requires.txt").write_text("\n".join([ + "libc.so.6()(64bit)", "libm.so.6(GLIBC_2.35)(64bit)", + "libgcc_s.so.1()(64bit)", "libxkbcommon.so.0()(64bit)", + "(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))", + ])) + self.app = MagicMock() + self.app.poll.return_value = None + self.channel = MagicMock() + self.stream = self.channel.makefile.return_value.__enter__.return_value + self.stream.readline.side_effect = [ + b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n', + ] + self.runtime = None + + def launch(*args, **kwargs): + self.runtime = Path(kwargs["env"]["XDG_RUNTIME_DIR"]) + self.assertTrue(self.runtime.is_dir()) + return self.app + + self.launch = self.start_patch(smoke.subprocess, "Popen", side_effect=launch) + self.start_patch(smoke.subprocess, "check_output", return_value="vectorcraft-cli 0.25.0\n") + self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel) + self.start_patch(smoke.time, "sleep") + + def start_patch(self, owner, name, **kwargs): + patcher = patch.object(owner, name, **kwargs) + result = patcher.start() + self.addCleanup(patcher.stop) + return result + + def assert_cleaned_up(self): + self.app.terminate.assert_called_once() + self.assertFalse(self.runtime.exists()) + + def test_success_records_inspection_and_removes_private_runtime(self): + smoke.run_smoke(self.results) + report = json.loads((self.results / "ui.inspect.json").read_text()) + self.assertEqual(report["result"], {"window": "fixture"}) + requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] + self.assertEqual(requests[0]["method"], "auth") + self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"]) + self.assert_cleaned_up() + + def test_missing_runtime_dependency_prevents_launch(self): + (self.results / "rpm-requires.txt").write_text("") + with self.assertRaisesRegex(RuntimeError, "Missing RPM requirement"): + smoke.run_smoke(self.results) + self.launch.assert_not_called() + + def test_child_exit_during_startup_is_a_failure(self): + self.app.poll.return_value = 1 + self.app.returncode = 1 + with self.assertRaisesRegex(RuntimeError, "exited during startup"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_connection_is_retried_until_ready(self): + self.connect.side_effect = [OSError("not ready"), self.channel] + smoke.run_smoke(self.results) + self.assertEqual(self.connect.call_count, 2) + self.assert_cleaned_up() + + def test_startup_timeout_stops_child(self): + self.connect.side_effect = OSError("not ready") + self.start_patch(smoke.time, "monotonic", side_effect=[0, 91]) + with self.assertRaisesRegex(RuntimeError, "did not become ready"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_auth_refusal_prevents_inspection(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":false}\n'] + with self.assertRaisesRegex(RuntimeError, "request failed: auth"): + smoke.run_smoke(self.results) + self.assertFalse((self.results / "ui.inspect.json").exists()) + self.assert_cleaned_up() + + def test_response_for_another_request_is_rejected(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', b'{"id":99,"ok":true}\n'] + with self.assertRaisesRegex(RuntimeError, "request failed: ui.inspect"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_malformed_response_still_stops_child(self): + self.stream.readline.side_effect = [b'not json\n'] + with self.assertRaises(json.JSONDecodeError): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_unresponsive_child_is_killed_after_termination_timeout(self): + self.app.wait.side_effect = [subprocess.TimeoutExpired("vectorcraft", 10), 0] + smoke.run_smoke(self.results) + self.app.kill.assert_called_once() + self.assert_cleaned_up() + + +if __name__ == "__main__": + unittest.main() 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..9937d6165c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,8 +50,8 @@ jobs: # 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,32 +59,6 @@ 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 diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml index dd4a4a02da..4ef372c40b 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -11,9 +11,9 @@ permissions: {} jobs: dispatch: - # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + # Enabled for automated scheduled producer completions on main. if: >- - false && github.repository == 'storytold/vectorcraft' && + github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_run' runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 0e963e43e1..c2224a81ba 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,9 @@ name: VectorCraft unsigned nightly -# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. -# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors. on: + schedule: + - cron: '30 6 * * *' workflow_dispatch: permissions: diff --git a/.github/workflows/release-rpm-smoke.yml b/.github/workflows/release-rpm-smoke.yml new file mode 100644 index 0000000000..61948e0f35 --- /dev/null +++ b/.github/workflows/release-rpm-smoke.yml @@ -0,0 +1,114 @@ +name: Release RPM smoke + +on: + workflow_dispatch: + inputs: + run-id: + description: Release run containing both RPM artifacts (empty selects the latest available pair) + type: string + default: "" + pull_request: + paths: + - .github/workflows/release-rpm-smoke.yml + - .github/scripts/release-rpm-smoke.py + - .github/scripts/tests/test_release_rpm_smoke.py + +permissions: {} + +jobs: + source: + permissions: + actions: read + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + run-id: ${{ steps.source.outputs.run-id }} + steps: + - id: source + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.run-id }} + run: | + candidates="$RUN_ID" + if [ -z "$candidates" ]; then + candidates=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow release.yml --branch release --limit 10 --json databaseId --jq '.[].databaseId') + fi + for candidate in $candidates; do + [[ "$candidate" =~ ^[0-9]+$ ]] + names=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$candidate/artifacts?per_page=100" --jq '.artifacts[] | select(.expired == false) | .name') + if grep -Fxq release-linux-x86_64 <<< "$names" && grep -Fxq release-linux-aarch64 <<< "$names"; then + printf 'run-id=%s\n' "$candidate" >> "$GITHUB_OUTPUT" + exit 0 + fi + done + echo '::error::No release run has both Linux package artifacts available' + exit 1 + smoke: + permissions: + contents: read + actions: read + needs: source + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + platform: + - {arch: x86_64, runner: ubuntu-24.04} + - {arch: aarch64, runner: ubuntu-24.04-arm} + distro: [fedora, rocky, opensuse] + runs-on: ${{ matrix.platform.runner }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - name: Download the release packages + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ needs.source.outputs.run-id }} + ARCH: ${{ matrix.platform.arch }} + run: | + [[ "$RUN_ID" =~ ^[0-9]+$ ]] + mkdir -p packages results + gh run view "$RUN_ID" --json headSha,url > results/source.json + gh run download "$RUN_ID" --name "release-linux-$ARCH" --dir packages + sha256sum packages/*.rpm > results/rpm-sha256.txt + - name: Install and start the RPM on the target distribution + env: + DISTRO: ${{ matrix.distro }} + run: | + sudo apt-get update -qq + sudo apt-get install -y xvfb + Xvfb :99 -screen 0 1440x900x24 -ac -nolisten tcp > results/xvfb.log 2>&1 & + for _attempt in {1..20}; do + [ -S /tmp/.X11-unix/X99 ] && break + sleep 1 + done + [ -S /tmp/.X11-unix/X99 ] + case "$DISTRO" in + fedora) image=fedora:latest ;; + rocky) image=rockylinux:10 ;; + opensuse) image=opensuse/tumbleweed:latest ;; + esac + docker pull "$image" + docker image inspect "$image" --format '{{json .RepoDigests}}' > results/container-digest.json + docker run --rm --ipc=host --name rpm-smoke -e DISTRO -e DISPLAY=:99 -e LIBGL_ALWAYS_SOFTWARE=1 \ + -v /tmp/.X11-unix:/tmp/.X11-unix:ro -v "$PWD/packages:/packages:ro" \ + -v "$PWD/results:/results" -v "$PWD/.github/scripts:/checks:ro" "$image" bash -euc ' + cat /etc/os-release > /results/os-release.txt + if [ "$DISTRO" = opensuse ]; then + zypper --non-interactive refresh + zypper --non-interactive install python3 Mesa-dri Mesa-libEGL1 libX11-6 libXcursor1 libXi6 libXrandr2 libxkbcommon0 libxkbcommon-x11-0 + zypper --non-interactive --no-gpg-checks install /packages/*.rpm + else + dnf -y install python3 mesa-dri-drivers mesa-libEGL libX11 libXcursor libXi libXrandr libxkbcommon libxkbcommon-x11 + dnf -y --nogpgcheck install /packages/*.rpm + fi + rpm -qp --requires /packages/*.rpm > /results/rpm-requires.txt + python3 /checks/release-rpm-smoke.py + ' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + if: always() + with: + name: rpm-smoke-${{ matrix.distro }}-${{ matrix.platform.arch }} + path: results/ + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 538d09cc31..ea3bf92583 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,6 +43,7 @@ jobs: app-name: vectorcraft app-title: VectorCraft macos-runner: macos-15 + macos-split-build: true craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index dde1f6f5a8..98e9c1d00a 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -21,4 +21,7 @@ jobs: # The reusable workflow defaults build-jobs to 2 so a cold instrumented # archive stays within hosted-runner memory (craft-common-actions#333). uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + python-coverage-source: .github/scripts + python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index 3cb674e4ae..772196967a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,12 +626,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -725,6 +719,17 @@ dependencies = [ "brotli-decompressor 5.0.3", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -1184,19 +1189,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1239,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "crc32fast", "flate2", @@ -1291,18 +1283,19 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "egui", ] @@ -1388,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "md-5", "rayon", @@ -1397,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "rayon", ] @@ -1451,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", ] @@ -1501,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", "serde_json", @@ -1542,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "gif", ] @@ -1626,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", ] @@ -1634,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,8 +1640,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "chrono", "fixed_decimal", "icu_calendar", @@ -1675,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "encoding_rs", "image", @@ -1809,17 +1804,26 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "chrono", "craft-codepage", "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -1835,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "serde", @@ -1846,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1858,12 +1862,12 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "async-channel", "async-io", "async-process", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -1873,6 +1877,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "rfd", "serde", "serde_json", @@ -1889,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1898,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -1922,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1933,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-eps", "flate2", @@ -1947,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "encoding_rs", "flate2", @@ -1958,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "dispatch2", "egui", @@ -1971,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1990,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-atomic", "craft-host", @@ -2007,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "fax", "hayro-ccitt", @@ -2018,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2039,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2051,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2076,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2091,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-atomic", "craft-behavior", @@ -2106,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2116,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2125,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2140,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2159,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-i18n", @@ -2175,7 +2181,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "accesskit", "craft-behavior", @@ -2213,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2224,7 +2230,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2242,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2263,7 +2269,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2284,7 +2290,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2303,7 +2309,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.22.1", "chrono", @@ -2335,7 +2341,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "serde", @@ -2346,7 +2352,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2356,7 +2362,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "js-sys", "serde_json", @@ -2367,7 +2373,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "winsafe", ] @@ -2375,7 +2381,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-appkit", "craft-atomic", @@ -2407,7 +2413,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2752,7 +2758,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", "emath", @@ -2785,7 +2791,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -2820,7 +2826,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "accesskit", "ahash", @@ -2839,7 +2845,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -2858,7 +2864,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "accesskit_winit", "arboard", @@ -2883,7 +2889,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "egui", @@ -2897,7 +2903,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", "egui", @@ -2910,7 +2916,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "dify", "eframe", @@ -2936,7 +2942,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "bytemuck", ] @@ -3017,7 +3023,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" dependencies = [ "ahash", "bytemuck", @@ -3043,7 +3049,11 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443" +source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", +] [[package]] name = "equivalent" @@ -3762,16 +3772,16 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3789,7 +3799,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3807,12 +3817,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "hayro-ccitt", @@ -4795,7 +4805,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4952,7 +4962,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8515,13 +8525,14 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.25.0" +version = "0.25.1" dependencies = [ "arboard", "block2 0.6.2", "chrono", "clipboard-win", "craft", + "craft-nightly", "eframe", "egui", "egui_extras", @@ -8558,7 +8569,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-affinity", "craft-image-codecs", @@ -8569,26 +8580,26 @@ dependencies = [ [[package]] name = "vectorcraft-apischema" -version = "0.25.0" +version = "0.25.1" dependencies = [ "serde_json", ] [[package]] name = "vectorcraft-brush" -version = "0.25.0" +version = "0.25.1" dependencies = [ "kurbo 0.13.1", "serde", "serde_json", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", ] [[package]] name = "vectorcraft-cad" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-dxf", "craft-image-codecs", @@ -8600,14 +8611,14 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", - "vectorcraft-pathops 0.25.0", + "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", "vectorcraft-text", ] [[package]] name = "vectorcraft-cli" -version = "0.25.0" +version = "0.25.1" dependencies = [ "log", "objc2-core-foundation", @@ -8618,7 +8629,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-mcp", "vectorcraft-render", "vectorcraft-svg", @@ -8630,7 +8641,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-cms", "craft-color-ui", @@ -8646,7 +8657,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.25.0" +version = "0.25.1" dependencies = [ "chrono", "craft-image-codecs", @@ -8662,13 +8673,13 @@ dependencies = [ "thiserror 2.0.21", "tiff", "vectorcraft-color", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "zune-jpeg", ] [[package]] name = "vectorcraft-effects" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "craft-svg", @@ -8678,8 +8689,8 @@ dependencies = [ "svgtypes 0.16.1", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.25.0", - "vectorcraft-pathops 0.25.0", + "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", "vectorcraft-plugins", "vectorcraft-text", "vectorcraft-three-d", @@ -8689,7 +8700,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.25.0" +version = "0.25.1" dependencies = [ "apple-native-keyring-store", "cfb", @@ -8738,10 +8749,10 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-eps", "vectorcraft-format", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-js", "vectorcraft-metafile", - "vectorcraft-pathops 0.25.0", + "vectorcraft-pathops 0.25.1", "vectorcraft-pdf", "vectorcraft-plugins", "vectorcraft-render", @@ -8761,7 +8772,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-eps", "craft-image-codecs", @@ -8782,9 +8793,9 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-eps", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-metafile", - "vectorcraft-pathops 0.25.0", + "vectorcraft-pathops 0.25.1", "vectorcraft-pdf", "vectorcraft-render", "vectorcraft-testkit", @@ -8793,7 +8804,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-gzip", "craft-vectorcraft-format", @@ -8805,7 +8816,7 @@ dependencies = [ "thiserror 2.0.21", "vectorcraft-brush", "vectorcraft-doc", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-testkit", ] @@ -8821,7 +8832,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.25.0" +version = "0.25.1" dependencies = [ "kurbo 0.13.1", "proptest", @@ -8832,7 +8843,7 @@ dependencies = [ [[package]] name = "vectorcraft-js" -version = "0.25.0" +version = "0.25.1" dependencies = [ "chrono", "craft-xml", @@ -8843,7 +8854,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft", "craft-image-codecs", @@ -8855,7 +8866,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-render", "vectorcraft-svg", "vectorcraft-testkit", @@ -8864,7 +8875,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "craft-metafile", @@ -8874,7 +8885,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-text", ] @@ -8891,19 +8902,19 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.25.0" +version = "0.25.1" dependencies = [ "kurbo 0.13.1", "linesweeper", "proptest", "thiserror 2.0.21", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-testkit", ] [[package]] name = "vectorcraft-pdf" -version = "0.25.0" +version = "0.25.1" dependencies = [ "aes 0.8.4", "chrono", @@ -8932,7 +8943,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-pdf", "vectorcraft-testkit", "vectorcraft-text", @@ -8940,7 +8951,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugin-worker" -version = "0.25.0" +version = "0.25.1" dependencies = [ "js-sys", "vectorcraft-plugins", @@ -8950,7 +8961,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "craft-vectorcraft-format", @@ -8962,7 +8973,7 @@ dependencies = [ "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-js", "vectorcraft-plugins", "wasmi", @@ -8973,7 +8984,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-gif", "craft-image-codecs", @@ -8991,7 +9002,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-plugins", "vectorcraft-testkit", "vectorcraft-text", @@ -9004,7 +9015,7 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.25.0" +version = "0.25.1" dependencies = [ "proptest", "unicode-properties", @@ -9012,7 +9023,7 @@ dependencies = [ [[package]] name = "vectorcraft-svg" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-docpath", "craft-image-codecs", @@ -9036,15 +9047,16 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", - "vectorcraft-pathops 0.25.0", + "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] [[package]] name = "vectorcraft-testkit" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "fax", @@ -9055,14 +9067,14 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-render", "vectorcraft-svg", ] [[package]] name = "vectorcraft-text" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft", "craft-fonts-build", @@ -9080,23 +9092,23 @@ dependencies = [ "unicode-script", "unicode-segmentation", "vectorcraft-doc", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vello_cpu", "write-fonts", ] [[package]] name = "vectorcraft-three-d" -version = "0.25.0" +version = "0.25.1" dependencies = [ "proptest", - "vectorcraft-geom 0.25.0", - "vectorcraft-pathops 0.25.0", + "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", ] [[package]] name = "vectorcraft-thumbnail-handler" -version = "0.25.0" +version = "0.25.1" dependencies = [ "png 0.18.1", "windows", @@ -9105,7 +9117,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "kurbo 0.13.1", @@ -9115,15 +9127,15 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.25.0", - "vectorcraft-pathops 0.25.0", + "vectorcraft-geom 0.25.1", + "vectorcraft-pathops 0.25.1", "vectorcraft-text", "vectorcraft-tools", ] [[package]] name = "vectorcraft-trace" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft-image-codecs", "image", @@ -9131,12 +9143,12 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", ] [[package]] name = "vectorcraft-ui-egui" -version = "0.25.0" +version = "0.25.1" dependencies = [ "bytemuck", "chrono", @@ -9160,7 +9172,7 @@ dependencies = [ "vectorcraft-engine", "vectorcraft-eps", "vectorcraft-format", - "vectorcraft-geom 0.25.0", + "vectorcraft-geom 0.25.1", "vectorcraft-pdf", "vectorcraft-plugins", "vectorcraft-render", @@ -9175,7 +9187,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.25.0" +version = "0.25.1" dependencies = [ "craft", "craft-web-api", @@ -10067,7 +10079,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", @@ -10404,7 +10416,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.25.0" +version = "0.25.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 7ad3e4cfeb..e1a20cac68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,55 +4,57 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.25.0" +version = "0.25.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -192,22 +194,22 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +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" } +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 557a23c91a..224fdbd9ac 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 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-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index ce4d1d3d44..30d529a5e7 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 = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index d17c96eaf7..3ec7da1b75 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true } # frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } +craft-nightly = { workspace = true } eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } egui_extras = { 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/build_flavor.rs b/apps/vectorcraft/src/build_flavor.rs index 9450a48972..93876b5cce 100644 --- a/apps/vectorcraft/src/build_flavor.rs +++ b/apps/vectorcraft/src/build_flavor.rs @@ -1,30 +1,13 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a -//! stable build, and a nightly build refuses to start without its profile. -use crate::launch_profile::Profile; -use std::ffi::OsString; +//! stable build, and a nightly build self-isolates into its canonical nightly profile root (or the +//! profile root supplied by ArtCraft Launcher). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open VectorCraft Nightly from ArtCraft Launcher".to_string()), - (BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()), - _ => Ok(()), - } -} - -pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { - desktop_session && flavor == BuildFlavor::NightlyV1 -} - -/// `--version` and `-V` on their own, before any other argument is read. -pub fn version_query(args: &[OsString]) -> bool { +/// An exact plain version query, before resolving any profile or environment paths. +pub fn version_query(args: &[std::ffi::OsString]) -> bool { matches!(args, [arg] if arg == "--version" || arg == "-V") } @@ -37,40 +20,19 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, version, version_query}; #[test] - fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { - assert!(needs_native_error(BuildFlavor::NightlyV1, true)); - assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); - assert!(!needs_native_error(BuildFlavor::Stable, true)); - assert!(!needs_native_error(BuildFlavor::Stable, false)); - } - - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err()); - } - - #[test] - fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { - assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1"); - assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)"); + fn plain_version_query_is_exact() { assert!(version_query(&["--version".into()])); assert!(version_query(&["-V".into()])); assert!(!version_query(&["--".into(), "--version".into()])); assert!(!version_query(&[])); } + + #[test] + fn version_labels_nightly_without_changing_stable() { + assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)"); + } } 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..4b660854f6 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -602,15 +602,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/launch_profile.rs b/apps/vectorcraft/src/launch_profile.rs index 12615dd81d..d986f28d71 100644 --- a/apps/vectorcraft/src/launch_profile.rs +++ b/apps/vectorcraft/src/launch_profile.rs @@ -1,130 +1,28 @@ -//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. -//! Stable launches retain their original arguments and directory policy. -//! -//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root -- [files…]`: the -//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file -//! even when it looks like one of them. The Launcher's version check -//! (`… --version`) is answered before the root is validated or touched. +//! Nightly-v1 bootstrap backed by [`craft_nightly`]. Selected before logging, updates, fonts or +//! saved state. Stable launches retain their original arguments and directory policy; direct +//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`], while ArtCraft +//! Launcher can supply `--launch-profile nightly-v1 --profile-root -- [args…]`. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; +pub use craft_nightly::NIGHTLY_V1_CONTRACT as VERSION; +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +static STABLE: Profile = Profile::Stable; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&STABLE) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook -/// runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".to_string()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".to_string()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".to_string()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".to_string()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".to_string()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()), - _ => Err("--launch-profile and --profile-root must be supplied together".to_string()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root -/// validator, so its portable and config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable) +pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::app_profile_spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default()) } /// The arguments a child of this process starts with: a nightly launch hands its profile on, so the -/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and -/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged. -/// Only `single_instance` starts a child, and macOS does not build it. +/// child opens the same private profile, and `--` keeps a file whose name starts with '-' a file. +/// Stable's child arguments are unchanged. Only `single_instance` starts a child, and macOS does +/// not build it. #[cfg(not(target_os = "macos"))] pub fn child_args(files: &[String]) -> Vec { child_args_for(current(), files) @@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec { #[cfg(not(target_os = "macos"))] fn child_args_for(profile: &Profile, files: &[String]) -> Vec { - let mut args: Vec = match profile { - Profile::Stable => Vec::new(), - Profile::NightlyV1(root) => { - vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()] - } - }; - args.push(OsString::from("--")); - args.extend(files.iter().map(OsString::from)); - args + let delimited: Vec = std::iter::once(OsString::from("--")).chain(files.iter().map(OsString::from)).collect(); + match profile { + Profile::Stable => delimited, + Profile::NightlyV1(root) => craft_nightly::launch_arguments(root, &delimited), + } } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::PathBuf; + + use craft_nightly::{BuildFlavor, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup}; + + use super::VERSION; + #[cfg(not(target_os = "macos"))] + use super::child_args_for; + use crate::profile_root::app_profile_spec; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -156,95 +57,72 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = app_profile_spec(); for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::default()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]); + let err = parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::default()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "art with spaces.svg"])); - let launch = parse(argv).unwrap(); + fn nightly_direct_launch_self_isolates_into_canonical_profile_root() { + let spec = app_profile_spec(); + let expected_root = canonical_profile_root("vectorcraft").unwrap(); + + let empty = parse_startup(BuildFlavor::NightlyV1, &spec, Vec::new(), &StartupOptions::default()).unwrap(); + assert_eq!(empty.profile, Profile::NightlyV1(expected_root.clone())); + assert!(empty.passthrough_args.is_empty()); + + let with_args = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--safe-mode", "art.svg"]), &StartupOptions::default()).unwrap(); + assert_eq!(with_args.profile, Profile::NightlyV1(expected_root)); + assert_eq!(with_args.passthrough_args, args(&["--safe-mode", "art.svg"])); + } + + #[test] + fn explicit_launcher_arguments_preserve_profile_root_and_user_args() { + let spec = app_profile_spec(); + let argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--profile-root", "art with spaces.svg"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "art with spaces.svg"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); - } - } - - #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = app_profile_spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); + for argv in [ + args(&[flag]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag]), + args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", flag]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); } } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); - } - - #[test] - fn a_joined_flag_form_is_refused() { - for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] { - let argv = vec![OsString::from(joined), OsString::from("--")]; - assert!(parse(argv).is_err()); + fn version_and_document_arguments_are_not_a_version_only_query() { + let spec = app_profile_spec(); + for flag in ["--version", "-V"] { + for argv in [ + args(&[flag, "art with spaces.svg"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag, "art with spaces.svg"]), + args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag, "art with spaces.svg"]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap(); + assert!(!launch.is_version_query()); + assert_eq!(launch.passthrough_args, args(&[flag, "art with spaces.svg"])); + } } } @@ -258,6 +136,7 @@ mod tests { #[cfg(not(target_os = "macos"))] #[test] fn a_nightly_child_inherits_the_selected_profile() { + let spec = app_profile_spec(); let root = PathBuf::from(absolute()); let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]); let expected = vec![ @@ -266,12 +145,12 @@ mod tests { OsString::from("--profile-root"), root.into_os_string(), OsString::from("--"), + OsString::from("--"), OsString::from("art.svg"), ]; assert_eq!(child, expected); - // The child's own parse finds the same profile and the file list. - let launch = parse(child).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, child, &StartupOptions::default()).unwrap(); assert!(launch.profile.is_nightly()); - assert_eq!(launch.args, args(&["--", "art.svg"])); + assert_eq!(launch.passthrough_args, args(&["--", "art.svg"])); } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 5a7d3e33ba..b603ed7960 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -112,6 +112,43 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled}; const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; const MIN_SIZE: [f32; 2] = [800.0, 500.0]; +/// Apply the saved main-window placement before the first frame. On a first launch the +/// framework maximizes the window when its default size would not fit the current screen. +fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option, wayland: bool) { + use craft::behavior::placement::{Defaults, Placement, place}; + use craft::behavior::{Monitor, MonitorKey}; + use winit::dpi::{LogicalSize, PhysicalPosition}; + + let handles: Vec<_> = window.available_monitors().collect(); + let monitors: Vec<_> = handles + .iter() + .map(|monitor| { + let size = monitor.size(); + let size = [size.width, size.height]; + let position = monitor.position(); + Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32) + }) + .collect(); + let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor)); + let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland); + let saved = store.get(craft::window::restore::MAIN).or_else(|| { + let old = legacy?; + let mut placement = Placement::new(old.size, window.scale_factor() as f32); + placement.position_px = old.pos; + placement.maximized = old.maximized; + placement.repaired() + }); + let placement = place(saved.as_ref(), &monitors, home, &defaults); + if let Some([x, y]) = placement.position_px { + window.set_outer_position(PhysicalPosition::new(x, y)); + } + let [width, height] = placement.normal.size; + let _ = window.request_inner_size(LogicalSize::new(width, height)); + if placement.maximized { + window.set_maximized(true); + } +} + /// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets /// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches /// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. @@ -359,15 +396,36 @@ 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)"); } @@ -384,58 +442,47 @@ fn channel_name() -> &'static str { /// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this /// app has no message box of its own before eframe starts (its dialogs are egui windows), so the -/// text goes to standard error, which a Launcher launch records. The desktop-session test still -/// decides whether a daily user would have seen it, for the message's wording. +/// text goes to standard error, which a Launcher launch records. fn report_launch_profile_error(error: &str) { eprintln!("VectorCraft launch profile: {error}"); - let desktop_session = cfg!(windows) - || cfg!(target_os = "macos") - || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); - if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { - eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile"); - } +} + +fn write_nightly_version() { + use std::io::Write as _; + let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION"))); + let _ = std::io::stdout().write_all(line.as_bytes()); } /// Selects the immutable launch profile before any startup service or side effect, and returns the /// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered). fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state. + // The launch profile is decided before the logger, updates, fonts or any saved state. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // A nightly answers its version before root validation, process identity, IPC or any window: - // plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`. A stable build leaves the answer to `read_command_line`, exactly as before. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) - { - use std::io::Write as _; - let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION"))); - let _ = std::io::stdout().write_all(line.as_bytes()); + // A plain nightly version query does not even need the OS home/data root to resolve. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + write_nightly_version(); + return None; + } + let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // A launcher version query also exits before process identity, IPC or any window. + // `craft_nightly::prepare_launch` skips root preparation for version queries. + // A stable build leaves the answer to `read_command_line`, exactly as before. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { + write_nightly_version(); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let nightly = early.profile.is_nightly(); let identity = if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable }; - let install = launch_profile::install(early.profile).and_then(|()| { - // Every data path follows the selected profile from here on: settings, logs, recovery, the - // user's libraries, plug-ins, caches and the single-instance record. - if let Some(root) = launch_profile::current().root() { - prefs_dir::profile::install_data_root(root.to_path_buf())?; - } - vectorcraft_ui_egui::os_window::select_identity(identity) - }); + // Every data path follows the selected profile from here on: settings, logs, recovery, the + // user's libraries, plug-ins, caches and the single-instance record. + let install = launch_profile::current() + .root() + .map_or(Ok(()), |root| prefs_dir::profile::install_data_root(root.to_path_buf())) + .and_then(|()| vectorcraft_ui_egui::os_window::select_identity(identity)); if let Err(error) = install { report_launch_profile_error(&error); std::process::exit(2); @@ -453,11 +500,11 @@ fn prepare_launch() -> Option> { // The window's identity, not the profile, failed: main's own failure status (1). std::process::exit(1); } - Some(early.args) + Some(early.passthrough_args) } /// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by -/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its +/// `prepare_launch`, leaving any user flags and files to open. A stable launch reads its /// arguments exactly as it always did. fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec { if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() } @@ -520,8 +567,9 @@ fn finish_pending_update(nightly: bool) { } fn main() -> std::process::ExitCode { - // The launch profile first: a nightly build without one is refused here, before the update - // helper, the logger, fonts or any saved state, and `--version` is answered here too. + // The launch profile first: a nightly build self-isolates or uses the Launcher's profile here, + // before the update helper, the logger, fonts or any saved state, and `--version` is answered + // here too. let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; let nightly = launch_profile::current().is_nightly(); #[cfg(windows)] @@ -695,14 +743,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) }); @@ -791,9 +839,13 @@ fn main() -> std::process::ExitCode { Box::new(move |cc| { let ctx = &cc.egui_ctx; let winit_window = cc.winit_window().cloned(); + let placement = placement_store(); + if let Some(window) = &winit_window { + restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland); + } let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) .app_id(vectorcraft_ui_egui::os_window::app_id()) - .placement(Arc::new(Mutex::new(placement_store()))) + .placement(Arc::new(Mutex::new(placement))) .frame(decision); let spec = match start_pen(&winit_window) { Some(pen) => spec.pen(pen), @@ -808,7 +860,7 @@ fn main() -> std::process::ExitCode { }; let (files, file_panels) = file_service(wake, folders); let files = Arc::new(files); - craft::host::Host::builder(AppInfo { + let host = craft::host::Host::builder(AppInfo { id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID, name: vectorcraft_ui_egui::os_window::name(), version: vectorcraft_ui_egui::os_window::version(), @@ -816,7 +868,8 @@ fn main() -> std::process::ExitCode { .i18n(vectorcraft_ui_egui::i18n::shared()) .settings(Arc::new(settings.clone())) .files(files.clone()) - .install(ctx); + .build(); + host.clone().install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -841,6 +894,7 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(winit_window.clone())); + app.host = Arc::new(host); app.adopt_context(&cc.egui_ctx); // A nightly is updated by the Launcher: it never checks for a stable release, which // would install this program's own updater over the nightly build. @@ -887,7 +941,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!( diff --git a/apps/vectorcraft/src/profile_root.rs b/apps/vectorcraft/src/profile_root.rs index 7f46e77766..d5ae707a17 100644 --- a/apps/vectorcraft/src/profile_root.rs +++ b/apps/vectorcraft/src/profile_root.rs @@ -1,264 +1,17 @@ -//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected -//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable -//! copy or an installation. +//! App-owned nightly profile specification for [`craft_nightly`]: describes VectorCraft's stable +//! directories, forbidden environment variables, portable markers, folder-only profile entries, and +//! extra installation/package boundaries so a nightly profile never overlaps stable state. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::{Path, PathBuf}; -use crate::prefs_dir::profile::PORTABLE_DATA_DIR; +use craft_nightly::AppProfileSpec; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} +use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS}; -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - other => Err(format!("nightly-v1 is not defined for this operating system ({other})")), - } - } +const STABLE_DIR_NAMES: [&str; 2] = ["VectorCraft", "vectorcraft"]; - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string()); - parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still -/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse -/// every launch, a valid private profile included. -fn canonical_future_entry(path: &Path) -> Result { - let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?; - let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?; - Ok(canonical_future(parent)?.join(name)) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or_else(|| "cannot establish the installation boundary".to_string())?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each -/// platform convention and the portable layout use, the eframe window state, the logs, the recovery -/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that -/// overlapped any of them would read, rewrite or prune stable's own state. -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // The settings folder (`profile.rs`) and the eframe window state, which eframe puts under - // `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id). - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("VectorCraft"))) - .collect::, _>>()?; - roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft")); - // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom - // install folder is not known here; the executable's own folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("VectorCraft")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("VectorCraft")); - } - } - roots - } - Platform::Linux => { - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft"))) - .collect::, _>>()?; - // The eframe window state, under the lowercased window id. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft")); - roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft")); - // The same folders at their HOME defaults: an XDG override moves this launch's own paths, - // not stable's, which stays where a launch without the override finds it. - for (directory, app) in - [(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")] - { - roots.push(required_base(env, "HOME")?.join(directory).join(app)); - } - // The stable Flatpak keeps its data in its own per-app folder. - roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/VectorCraft"), - library.join("Application Support/ai.storyteller.vectorcraft"), - library.join("Caches/VectorCraft"), - library.join("Caches/ai.storyteller.vectorcraft"), - library.join("Preferences/VectorCraft"), - library.join("Preferences/ai.storyteller.vectorcraft.plist"), - library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"), - home.join("Applications/VectorCraft.app"), - PathBuf::from("/Applications/VectorCraft.app"), - ] - } - }; - roots.push(installation_boundary(platform, exe)?); - let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::, _>>()?; - if platform == Platform::Linux { - for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] { - fences.push(canonical_future_entry(Path::new(entry))?); - } - } - Ok(fences) -} - -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let target = chosen.join(name); - match std::fs::symlink_metadata(&target) { - Ok(metadata) if !metadata.is_dir() => { - return Err(format!("the nightly {label} must be a directory inside its selected profile")); - } - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), - } - let child = canonical_future(&target)?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} - -/// Every existing entry directly in the profile (settings, logs, the user's libraries and so on) must -/// resolve inside it, so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) -} - -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - #[cfg(all(windows, feature = "wgpu"))] - { - use winsafe::{HFILE, co}; - let (file, _) = HFILE::CreateFile( - path.to_str().ok_or("the nightly profile file path is not textual")?, - co::GENERIC::default(), - Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), - None, - co::DISPOSITION::OPEN_EXISTING, - co::FILE_ATTRIBUTE::NORMAL, - Some(co::FILE_FLAG::OPEN_REPARSE_POINT), - None, - None, - ) - .map_err(|e| e.to_string())?; - let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; - if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) { - return Err("the nightly profile file must not be an alias or directory".into()); - } - if info.nNumberOfLinks != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - #[cfg(all(windows, not(feature = "wgpu")))] - { - use std::os::windows::fs::MetadataExt as _; - const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10; - const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; - if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 { - return Err("the nightly profile file must not be an alias or directory".into()); - } - } - let _ = (path, metadata); - Ok(()) -} +const FORBIDDEN_ENV_VARS: [&str; 2] = ["VECTORCRAFT_CONFIG_DIR", "VECTORCRAFT_NO_PREFS"]; const PROFILE_FOLDERS: [&str; 18] = [ "Data Recovery", @@ -281,397 +34,207 @@ const PROFILE_FOLDERS: [&str; 18] = [ "Libraries", ]; -/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to -/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated -/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - path.ancestors().enumerate().any(|(depth, ancestor)| { - crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file()) - && (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) +/// Builds VectorCraft's [`AppProfileSpec`] for [`craft_nightly`]. +pub fn app_profile_spec() -> AppProfileSpec { + AppProfileSpec { + app_id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID, + display_name: vectorcraft_ui_egui::os_window::APP_NAME, + stable_dir_names: &STABLE_DIR_NAMES, + stable_package_id: vectorcraft_ui_egui::os_window::APP_ID, + nightly_package_id: vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: &FORBIDDEN_ENV_VARS, + portable_markers: &PORTABLE_MARKERS, + folder_only_entries: &PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(), + } } -/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping -/// it injected lets the boundary tests exercise the real policy without starting the app. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string()); - } - // The app turns preferences off whenever the variable is present, empty value included. - if env("VECTORCRAFT_NO_PREFS").is_some() { - // A run without preferences keeps nothing: its own profile would stay unused and the app - // would log to standard error only, so it is never a nightly launch. - return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string()); - } - let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID; - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty()) - && id.to_string_lossy().as_ref() != nightly_flatpak +fn extra_forbidden_roots() -> Vec { + extra_forbidden_roots_with(|key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) +} + +fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Vec { + let mut roots = Vec::new(); + + #[cfg(target_os = "windows")] { - // `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak - // (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other - // instance, the stable app's included, would put this profile inside another app's tree. - return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy())); + if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("VectorCraft")); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs(&env, key) { + roots.push(base.join("ArtCraft").join("VectorCraft")); + } + } } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable VectorCraft installation or its VectorCraftData settings folder".to_string()); - } - let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".to_string()); - } - // Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the - // private profile. - private_subdirectory(&chosen, "Data Recovery", "recovery folder")?; - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(all(unix, not(target_os = "macos")))] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + if let Some(home) = non_empty_abs(&env, "HOME") { + roots.push(home.join(".var").join("app").join(vectorcraft_ui_egui::os_window::APP_ID)); + } + for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] { + roots.push(PathBuf::from(entry)); + } } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".to_string()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{}.plist", vectorcraft_ui_egui::os_window::APP_ID))); + roots.push(library.join("Saved Application State").join(format!("{}.savedState", vectorcraft_ui_egui::os_window::APP_ID))); + roots.push(home.join("Applications").join("VectorCraft.app")); + } + roots.push(PathBuf::from("/Applications/VectorCraft.app")); } - private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + if let Some(exe) = exe { + if let Some(parent) = exe.parent() { + roots.push(parent.join(PORTABLE_DATA_DIR)); + } + #[cfg(target_os = "macos")] + if let Some(bundle_parent) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))).and_then(Path::parent) + { + roots.push(bundle_parent.join(PORTABLE_DATA_DIR)); + } + } + + roots } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; - use std::collections::BTreeMap; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::ffi::OsString; + use std::fs; + #[cfg(unix)] + use std::path::PathBuf; - /// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the - /// fence can be checked for every platform on any host. - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::validate_and_prepare_root; - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("vectorcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/vectorcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } - } - - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - self.check_with(platform, root, |_| Ok(())) - } - - fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable) - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); - } - } - - const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac]; + use super::{FORBIDDEN_ENV_VARS, PROFILE_FOLDERS, STABLE_DIR_NAMES, app_profile_spec, extra_forbidden_roots_with}; + use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS}; #[test] - fn a_private_profile_is_accepted_on_every_platform() { - let fixture = Fixture::new(); - for platform in PLATFORMS { - let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft")); - let resolved = fixture.check(platform, &root).unwrap(); - assert!(resolved.is_dir(), "{platform:?}"); - assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}"); - std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap(); - } + fn spec_preserves_vectorcraft_invariants() { + let spec = app_profile_spec(); + assert_eq!(spec.app_id, "vectorcraft"); + assert_eq!(spec.display_name, "VectorCraft"); + assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES); + assert_eq!(spec.stable_package_id, "ai.storyteller.vectorcraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.vectorcraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, &FORBIDDEN_ENV_VARS); + assert_eq!(spec.portable_markers, &PORTABLE_MARKERS); + assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS); } #[test] - fn stable_settings_folders_are_refused_on_every_platform() { - let fixture = Fixture::new(); - let stable = [ - (Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))), - (Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))), - (Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))), - (Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))), - (Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))), - ]; - for (platform, stable) in stable { - let stable = stable.unwrap(); - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = Cell::new(false); - let result = fixture.check_with(platform, &candidate, |_| { - probed.set(true); - Ok(()) - }); - assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get(), "a refused root is rejected before the writable probe"); - } - } - } + fn extra_forbidden_roots_fences_platform_installs_and_portable_data() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let exe = tmp.path().join("install/vectorcraft"); + let roots = extra_forbidden_roots_with( + |key| match key { + "HOME" | "LOCALAPPDATA" | "ProgramFiles" => Some(home.clone().into_os_string()), + _ => None, + }, + Some(&exe), + ); + assert!(roots.contains(&tmp.path().join("install").join(PORTABLE_DATA_DIR))); - #[test] - fn the_install_folder_and_the_entry_points_are_refused() { - let fixture = Fixture::new(); - for platform in PLATFORMS { - let install = fixture.exe.parent().unwrap(); - assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder"); - assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install"); - } - } - - #[test] - fn an_inherited_config_or_no_prefs_override_is_refused() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - for (key, value) in [ - ("VECTORCRAFT_CONFIG_DIR", "/elsewhere"), - ("VECTORCRAFT_NO_PREFS", "1"), - // The app turns preferences off on presence, so an empty value is a run too. - ("VECTORCRAFT_NO_PREFS", ""), - ("FLATPAK_ID", "ai.storyteller.vectorcraft"), - ] { - for platform in PLATFORMS { - let result = validate_for( - platform, - &root, - |name| if name == key { Some(value.into()) } else { fixture.get(name) }, - Some(&fixture.exe), - |_| Ok(()), - ); - let refused = result.is_err(); - // A Flatpak instance only keeps the stable app's sockets on native Unix packages. - assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}"); - if refused { - assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})"); - } else if root.exists() { - // The accepted case validated the root, which creates it: start the next one clean. - std::fs::remove_dir_all(&root).expect("remove the accepted launch's root"); - } - } - } - } - - #[test] - fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() { - let fixture = Fixture::new(); - let root = fixture.root.join("flatpak profile"); - for (id, accepted) in - [(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)] + #[cfg(target_os = "windows")] { - let result = validate_for( - Platform::Linux, - &root, - |name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) }, - Some(&fixture.exe), - |_| Ok(()), - ); - assert_eq!(result.is_ok(), accepted, "{id}"); - let _ = std::fs::remove_dir_all(&root); + assert!(roots.contains(&home.join("Programs").join("ArtCraft").join("VectorCraft"))); + assert!(roots.contains(&home.join("ArtCraft").join("VectorCraft"))); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(roots.contains(&home.join(".var/app/ai.storyteller.vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/bin/vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/local/bin/vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/opt/vectorcraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.vectorcraft.plist"))); + assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.vectorcraft.savedState"))); + assert!(roots.contains(&home.join("Applications/VectorCraft.app"))); + assert!(roots.contains(&PathBuf::from("/Applications/VectorCraft.app"))); } } #[test] - fn a_portable_copy_and_its_data_folder_are_refused() { - let fixture = Fixture::new(); - let portable = fixture.root.join("portable copy"); - let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR); - std::fs::create_dir_all(&data).unwrap(); - std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap(); - std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap(); - for platform in PLATFORMS { - for candidate in [&data, &data.join("nested nightly")] { - let probed = Cell::new(false); - let result = fixture.check_with(platform, candidate, |_| { - probed.set(true); - Ok(()) - }); - assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get()); - assert!(!data.join("nested nightly").exists()); - assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change"); - } + fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_only_entries() { + let tmp = tempfile::tempdir().unwrap(); + let private = tmp.path().join("nightly-reopen"); + let mut spec = app_profile_spec(); + spec.forbidden_env_vars = &[]; + + let canonical = validate_and_prepare_root(&private, &spec).unwrap(); + assert_eq!(canonical, fs::canonicalize(&private).unwrap()); + + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + fs::write(canonical.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + fs::create_dir(canonical.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), canonical); + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + assert_eq!(fs::read(canonical.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen"); + } + + for name in PROFILE_FOLDERS { + let path = canonical.join(name); + fs::remove_dir(&path).unwrap(); + fs::write(&path, b"not a directory").unwrap(); + assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} must stay a directory"); + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); } - // A merely similar name is not the portable settings folder. - let similar = fixture.root.join("VectorCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &similar).is_ok()); } #[cfg(unix)] #[test] - fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - std::fs::create_dir_all(&root).unwrap(); - let external = fixture.root.join("stable-document"); - std::fs::write(&external, b"stable bytes").unwrap(); + fn symlink_inside_profile_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let private = tmp.path().join("nightly"); + fs::create_dir_all(&private).unwrap(); + let external = tmp.path().join("stable-document"); + fs::write(&external, b"stable bytes").unwrap(); + + let mut spec = app_profile_spec(); + spec.forbidden_env_vars = &[]; + for name in ["Data Recovery", "Swatches"] { - let alias = root.join(name); + let alias = private.join(name); std::os::unix::fs::symlink(&external, &alias).unwrap(); - assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias"); - std::fs::remove_file(&alias).unwrap(); + assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} alias"); + fs::remove_file(&alias).unwrap(); } - assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); - } - - #[cfg(unix)] - #[test] - fn a_dangling_link_or_a_linked_ancestor_is_refused() { - let fixture = Fixture::new(); - let elsewhere = fixture.root.join("elsewhere"); - std::fs::create_dir_all(&elsewhere).unwrap(); - let linked = fixture.root.join("nightly"); - std::os::unix::fs::symlink(&elsewhere, &linked).unwrap(); - // Canonical resolution keeps a link's target: a profile reached through one is fine, but it - // is judged (and named) as its target, so nothing is written under the link. - let resolved = fixture.check(Platform::Linux, &linked).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap()); - std::fs::remove_file(&linked).unwrap(); - let dangling = fixture.root.join("dangling/nightly"); - std::fs::create_dir_all(dangling.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap(); - assert!(fixture.check(Platform::Linux, &dangling).is_err()); + assert_eq!(fs::read(&external).unwrap(), b"stable bytes"); } #[test] - fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() { - let fixture = Fixture::new(); - let xdg = fixture.root.join("override"); - std::fs::create_dir_all(&xdg).unwrap(); - let config = fixture.home().join(".config/vectorcraft"); - let data = fixture.home().join(".local/share/vectorcraft"); - for stable in [config.clone(), data.clone()] { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let result = validate_for( - Platform::Linux, - &candidate, - |name| match name { - "XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()), - _ => fixture.get(name), - }, - Some(&fixture.exe), - |_| Ok(()), - ); - assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}"); - } - } - assert!(!config.exists() && !data.exists(), "a refused root creates nothing"); - } - - #[cfg(unix)] - #[test] - fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() { - let fixture = Fixture::new(); - let bin = fixture.root.join("entry/bin"); - std::fs::create_dir_all(&bin).unwrap(); - let entry = bin.join("vectorcraft"); - std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap(); - // The shared resolver refuses the dangling link, as a profile root must be. - assert!(canonical_future(&entry).is_err()); - assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft")); - } - - #[test] - fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only"))); - assert!(result.unwrap_err().contains("not writable")); - } - - #[test] - fn nightly_profile_reopens_after_saving_settings_and_session_state() { - let fixture = Fixture::new(); - for platform in PLATFORMS { - let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); - assert_eq!(fixture.check(platform, &private).unwrap(), private); - for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } - } - - #[test] - fn the_platform_case_rules_are_the_file_systems_ones() { - let fixture = Fixture::new(); - let upper = fixture.root.join("NIGHTLY"); - assert!(fixture.check(Platform::Linux, &upper).is_ok()); - let stable_mac = fixture.home().join("library/application support/vectorcraft"); - assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively"); + fn non_empty_abs_ignores_empty_and_relative_values() { + let env = |key: &str| match key { + "EMPTY" => Some(OsString::new()), + "RELATIVE" => Some(OsString::from("relative/path")), + _ => None, + }; + assert!(super::non_empty_abs(&env, "EMPTY").is_none()); + assert!(super::non_empty_abs(&env, "RELATIVE").is_none()); + assert!(super::non_empty_abs(&env, "MISSING").is_none()); } } diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index 249309fa87..4dba61d6b4 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -155,8 +155,8 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> { } /// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-' -/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the -/// child would refuse to start without one. +/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), so the +/// child opens the same private profile. fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command { let mut command = std::process::Command::new(exe); command.args(super::launch_profile::child_args(files)); 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/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/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 92977884cf..80876c409a 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -24,3 +24,7 @@ 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/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/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 &'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}; diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 4d4eb9cdf8..2f56079b18 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; @@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec { "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", has_selection, bridge )] @@ -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/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/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/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/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..bac821ab90 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -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/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/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 066c6fc63f..ac66cb8e65 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -172,14 +172,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/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index cecf216b24..b2d6098e56 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -267,6 +267,8 @@ thread_local! { pub(crate) static FORMS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread. pub(crate) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many objects [`matches`] looked at on this thread. + pub(crate) static OBJECTS_WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; } impl Form { @@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result> { let mut cache = st.global_edit_forms.0.borrow_mut(); let mut pass = cache.forms.pass(); super::select::walk_selectable(d, st.isolation, |n| { + #[cfg(test)] + OBJECTS_WALKED.with(|c| c.set(c.get() + 1)); if n.id == *id || out.len() >= MAX_MEMBERS { return false; } @@ -1075,34 +1079,178 @@ pub fn highlights(s: &Session) -> std::sync::Arc { out } -/// [`similar`]'s outlines as of a document revision and the options they were found with. -pub type SimilarCache = std::cell::RefCell)>>; +/// [`similar`]'s outlines as of a document revision, with what they were found from. +pub type SimilarCache = std::cell::RefCell>; + +/// [`similar`]'s outlines and what they were found from. +#[derive(Clone, Debug)] +pub struct Similar { + revision: u64, + options: Options, + /// The document, the one selected object and the isolated object they were found with. + doc: Arc, + key: NodeId, + isolation: Option, + out: Arc, +} /// Before Global Edit starts: with one supported object selected, the outlines of the other /// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas /// shows them as soon as the object is selected. None while an interaction (a drag) is in /// progress, or when fewer than two objects would be taken. Kept per document revision and -/// options, as finding them walks the whole document. +/// options, as finding them walks the whole document. After an edit that replaced only the +/// selected object, and left what the others are compared with as it was (a move), the outlines +/// found before are kept without a walk. pub fn similar(s: &Session) -> std::sync::Arc { let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() }; - if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 { + // Global Edit is refused while an object of a dynamic symbol instance's art is selected. + if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() { return NO_HIGHLIGHTS.clone(); } let o = &s.global_edit_options; - if let Some((rev, opts, out)) = &*st.similar_outlines.borrow() - && *rev == st.revision - && opts == o + let key = st.selection.objects[0]; + if let Some(c) = &mut *st.similar_outlines.borrow_mut() + && c.options == *o + && c.key == key + && c.isolation == st.isolation + && (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key)) { - return out.clone(); + c.revision = st.revision; + c.doc = st.doc.clone(); + return c.out.clone(); } let out = Highlights::new(match matches(s, o) { Ok(m) if m.len() >= 2 => outlines(st, &m), _ => vec![], }); - *st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone())); + *st.similar_outlines.borrow_mut() = + Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() }); out } +/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both? +/// True when the layers differ only in `key` and in the layers and groups that hold it (the same +/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the +/// rest of the document is the same. A group that holds `key` is never like it (its form holds +/// `key`'s and more), so the walk looks into it before and after alike. +fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool { + let mut found = None; + let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| { + a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art) + }; + // Everything else in the document (artboards, symbol settings, editing modes) as it was: the + // symbols' art is compared on its own, as one copy when no edit changed it. + let rest = |d: &Document| { + let mut d = d.clone(); + d.layers.clear(); + d.symbols.clear(); + d + }; + if then.symbols.len() != now.symbols.len() + || !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b)) + || rest(then) != rest(now) + || !changed_only(&then.layers, &now.layers, key, &mut found) + { + return false; + } + found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes())) +} + +/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way +/// to it? `found` takes the two versions of `key` when it changed. +fn changed_only<'a>(then: &'a [Arc], now: &'a [Arc], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool { + if then.len() != now.len() { + return false; + } + then.iter().zip(now).all(|(a, b)| { + if Arc::ptr_eq(a, b) { + return true; + } + if a.id != b.id { + return false; + } + if a.id == key { + return found.replace((a, b)).is_none(); + } + match (holder_children(a), holder_children(b)) { + (Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found), + _ => false, + } + }) +} + +/// The objects in a layer or a group. +fn holder_children(n: &Node) -> Option<&[Arc]> { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children), + _ => None, + } +} + +/// Are two versions of a layer or a group the same apart from the objects in them? +fn same_holder(a: &Node, b: &Node) -> bool { + let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a; + let kinds = match (kind, &b.kind) { + ( + NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images }, + NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di }, + ) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di, + (NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c, + _ => false, + }; + kinds + && *id == b.id + && *name == b.name + && *visible == b.visible + && *locked == b.locked + && *opacity == b.opacity + && *blend == b.blend + && *isolate == b.isolate + && *knockout == b.knockout + && *knockout_shape == b.knockout_shape + && *appearance == b.appearance + && *bbox_angle == b.bbox_angle + && *extras == b.extras +} + +/// How far apart two versions of the selected object's form may lie, in its unit box, and how much +/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a +/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in +/// its unit box by a transform that includes the move), well within this. +const KEPT: f64 = 1e-12; + +/// Are two versions of the selected object compared with the other objects in the same way by +/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective +/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in +/// them? +fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool { + let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0); + fn same_look(a: &Node, b: &Node) -> bool { + fill_of(a) == fill_of(b) + && stroke_of(a) == stroke_of(b) + && match (a.children(), b.children()) { + (Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)), + (x, y) => x.is_none() && y.is_none(), + } + } + if !(supported(a) && supported(b)) { + return false; + } + let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false }; + let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs()); + let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) { + (Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()), + (x, y) => x.is_none() && y.is_none(), + }; + f.tag == g.tag + && f.symbols == g.symbols + && f.points.len() == g.points.len() + && f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT) + && fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y)) + && sizes + && same_look(a, b) +} + /// The outlines of `members` that are not selected, hold no selected object and sit inside no /// selected object, in their layer's color. fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines { diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 21f3661c89..ee369453e6 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 ), @@ -996,6 +996,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 +1060,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 +1083,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 +1126,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 +1163,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 +1185,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 1a15e44aa3..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; @@ -192,7 +197,11 @@ fn apply_transform_moving_guides( if copy { vec![] } else { ids } } else { let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; - s.edit(label, |d, sel| { + // 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<(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 // loop below transforms only the copies. @@ -229,9 +238,14 @@ fn apply_transform_moving_guides( transform_node(n, xf, sc, objects); } } + // 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| 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 { @@ -248,7 +262,10 @@ fn apply_transform_moving_guides( targets.extend(d.transform_ruler_guides(sel, xf)); } Ok(targets) - })? + })?; + let st = s.doc_mut()?; + st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5]))); + targets }; let st = s.doc_mut()?; if st.interaction.is_none() { @@ -266,6 +283,49 @@ fn apply_transform_moving_guides( Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) } +/// The node at index path `path` of `d`, shared. +fn node_arc(d: &Document, path: &[usize]) -> Option> { + let (first, rest) = path.split_first()?; + let mut cur = d.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur.clone()) +} + +/// 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`, 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 = |(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; + } + // 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(); + for (_, n) in held { + n.walk(&mut |c| { + moved.insert(c.id); + }); + } + let sel = &st.selection; + let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id)); + if !shown.all(|id| moved.contains(&id)) { + return None; + } + Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() }) +} + /// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction /// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot /// back first). These are the copies the interaction keeps when they were made of that snapshot for @@ -378,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..9b498f1ca8 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. @@ -608,16 +608,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, } } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 0f0ca215c3..abe4aeb194 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -84,6 +84,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", @@ -410,6 +411,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/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/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/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 e1bb6df83a..88aee55d33 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -203,6 +203,36 @@ 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 +/// they follow, no pass after the edit). A view that drew the selection of `from` can +/// move what it drew by `by` instead of building it again. It holds the documents as +/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches. +#[derive(Clone, Debug)] +pub struct Moved { + pub from: std::sync::Weak, + pub to: std::sync::Weak, + pub by: vectorcraft_geom::Vec2, + /// The selection the move was made with, which is also the selection after it. + pub selection: Selection, } /// A selection of objects alone ([`objects_only`]) with the document it was checked or read in: @@ -302,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); @@ -522,6 +554,8 @@ impl DocState { measured_in_own: None, inline_resolved: None, selection_record: None, + outside_live_paint: Default::default(), + moved: None, } } /// The [`SelectionRecord`] of the selection now: `None` when the document or the selected @@ -539,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..ce6023fb4e 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"] { 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 e417895424..fb2115190c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -512,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; -pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView}; +pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; 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..0143c46f9b 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`]), @@ -94,6 +97,7 @@ use vectorcraft_js::{ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; +mod save_open; mod tags; mod text; mod variables; @@ -172,7 +176,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 +207,14 @@ pub(super) struct State { editing: Cell>, locked: RefCell>, saving: Cell, + /// `app.userInteractionLevel` ([`save_open`]). + save_options: save_open::State, text: text::TextState, presets: RefCell>>, preset_bytes: Cell, preset_limit: u64, vars: variables::Handles, + tool: Cell>, } impl State { @@ -219,6 +227,12 @@ impl State { pub(super) fn saving(&self) -> bool { self.saving.get() } + + /// 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 +620,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 +643,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 +867,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 +910,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 +923,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 +1045,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 +1079,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 +1535,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 +1620,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 +2113,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 +2154,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 +2165,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 +2178,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 +2190,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 +2365,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 +2381,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. @@ -2812,7 +2953,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) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -2842,6 +2983,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 +2991,7 @@ 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(super::actions::app_members(l)); let preset = { let l = link.clone(); @@ -2858,8 +3001,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 +3040,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,9 +3070,8 @@ 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(save_open::document_members(l)); document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); classes.push(class("Document", None, document, None)); @@ -3039,6 +3182,7 @@ 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.push(class( "Layer", None, @@ -3066,6 +3210,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..805ead2eef 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -367,16 +367,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 +398,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 +410,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())) @@ -438,10 +440,10 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { 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 = path_items(h, st)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; 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}"))); 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..510364d249 --- /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. +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. +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`]). +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. +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..f386b4dc68 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2647,7 +2647,15 @@ impl Session { 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) } 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/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 9f1678ee4b..41a5e34707 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -118,6 +118,7 @@ mod livecorners; mod maskview; pub(super) mod menucmds; mod mesh_picks; +mod moved; mod nativefile; mod newart; mod newdoc; @@ -190,6 +191,7 @@ mod script_include; mod script_io; mod script_modules; mod script_run; +mod script_save_open; mod script_scriptui; mod script_styles; mod script_tags; @@ -1515,6 +1517,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"), 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..adb5d04af5 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] 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/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 076816e994..118d0aea56 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); let before = made(); assert_eq!(highlights(&s).len(), 39); - assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged"); + assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged"); sel(&mut s, &[copies[0]]); s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); sel(&mut s, &[copies[1]]); @@ -156,6 +156,207 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { assert_eq!(crate::cmd::globaledit::match_count(&s), 38); } +#[test] +fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() { + use crate::cmd::globaledit::{OBJECTS_WALKED, highlights}; + let walked = || OBJECTS_WALKED.with(std::cell::Cell::get); + // The outlines `highlights` gives, and how many objects it looked at for them. + let shown = |s: &Session| { + let before = walked(); + let out = highlights(s); + (out, walked() - before) + }; + // The outlines in each layer color. + let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::>(); + // The outlines a walk finds, the options set again so that nothing is kept. + let fresh = |s: &mut Session| { + let size = s.global_edit_options.size; + s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap(); + highlights(s); + s.execute("select.globalEditOptions", &json!({"size": size})).unwrap(); + let before = walked(); + let out = highlights(s); + assert!(walked() > before, "a walk"); + paths(&out) + }; + let mut s = session(); + let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3); + let copies: Vec = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect(); + sel(&mut s, &[key]); + let (first, n) = shown(&s); + assert_eq!(first.len(), 39); + assert!(n >= 40, "the first preview walks every object"); + + // The move rounds the form in its unit box differently; the same objects are like it. + s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap(); + let (out, n) = shown(&s); + assert_eq!(n, 0, "a move of the selected object alone compares the others as before"); + assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked"); + assert_eq!(paths(&out), fresh(&mut s)); + + // Another object moved: it is shown where it is now. + sel(&mut s, &[copies[0]]); + s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap(); + sel(&mut s, &[key]); + let (out, n) = shown(&s); + assert!(n > 0, "another object changed"); + let moved = node(&s, copies[0]).stroke_path().unwrap(); + assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now"); + assert_eq!(paths(&out), fresh(&mut s)); + + // The selected object took another shape: none of the squares is like it. + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let (out, n) = shown(&s); + assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shown(&s).0.len(), 39); + + // With Size, a larger copy of the selected square is another size. + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + assert_eq!(shown(&s).0.len(), 39); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let (out, n) = shown(&s); + assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.globalEditOptions", &json!({"size": false})).unwrap(); + + // With Appearance, another fill on the selected square leaves the others out. + s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap(); + assert_eq!(shown(&s).0.len(), 39); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + let (out, n) = shown(&s); + assert!(n > 0 && out.is_empty(), "the others have another fill now"); + s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap(); + + // Reflected, the selected kite keeps its size but is no longer like its copy. + let lone = kite(&mut s, 0.0, 500.0, 1.0); + kite(&mut s, 200.0, 500.0, 1.0); + sel(&mut s, &[lone]); + assert_eq!(shown(&s).0.len(), 1); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let (out, n) = shown(&s); + assert!(n > 0 && out.is_empty(), "a reflected copy is not like it"); +} + +#[test] +fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + rect(&mut s, 40.0, 0.0, 10.0, 10.0); + rect(&mut s, 60.0, 0.0, 10.0, 10.0); + sel(&mut s, &[key]); + assert_eq!(highlights(&s).len(), 3); + s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [key]); + assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out"); +} + +#[test] +fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + rect(&mut s, 20.0, 0.0, 10.0, 10.0); + rect(&mut s, 1100.0, 100.0, 10.0, 10.0); + s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap(); + sel(&mut s, &[key]); + assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out"); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + sel(&mut s, &[key]); + assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now"); +} + +#[test] +fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap()); + s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap(); + s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap(); + sel(&mut s, &[key]); + assert!(highlights(&s).is_empty(), "the other instance is on the canvas"); + // The symbol's art drawn 400 pt to the left: the other instance lies on the artboard. + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let art = std::sync::Arc::make_mut(&mut d.symbols[0].art); + art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default()); + st.revision += 1; + assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now"); +} + +#[test] +fn a_symbol_instance_put_in_perspective_has_another_size() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap(); + let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0); + let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap()); + s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap(); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + sel(&mut s, &[key]); + assert_eq!(highlights(&s).len(), 1); + let size = |s: &Session| bounds(s, key).size(); + let was = size(&s); + s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap(); + sel(&mut s, &[key]); + assert_ne!(size(&s), was, "the projection changes the instance's size"); + assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had"); +} + +#[test] +fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() { + use crate::cmd::globaledit::highlights; + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap()); + s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap(); + sel(&mut s, &[inst]); + assert_eq!(highlights(&s).len(), 1); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [inst]); + assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art"); + sel(&mut s, &[inst]); + assert_eq!(highlights(&s).len(), 1, "the whole instance again"); +} + +#[test] +fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() { + use crate::cmd::globaledit::{OBJECTS_WALKED, highlights}; + let walked = || OBJECTS_WALKED.with(std::cell::Cell::get); + let mut s = session(); + let group = |s: &mut Session, ids: &[NodeId]| { + sel(s, ids); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + }; + // A group of two squares inside an outer group with a third square, and a copy of both: the + // copy's inner group is like the selected inner group. + let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)]; + let inner = group(&mut s, &a); + let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + let outer = group(&mut s, &[inner, third]); + let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)]; + let inner_copy = group(&mut s, &b); + let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0); + group(&mut s, &[inner_copy, third_copy]); + sel(&mut s, &[inner]); + let first = highlights(&s); + assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one"); + assert!(!first.is_empty()); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = walked(); + assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first)); + assert_eq!(walked(), before, "the outer group changed with the selected group only"); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + s.execute("select.globalEditOptions", &json!({"size": false})).unwrap(); + assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same"); + assert!(walked() > before); +} + #[test] fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() { let mut s = session(); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 0394fb18fa..2806cdd925 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); diff --git a/crates/engine/src/tests/moved.rs b/crates/engine/src/tests/moved.rs new file mode 100644 index 0000000000..1b70d4acf8 --- /dev/null +++ b/crates/engine/src/tests/moved.rs @@ -0,0 +1,127 @@ +//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far +//! it went, and only when every object the selection shows is the one before it, moved that far. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::Vec2; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn doc(s: &Session) -> Arc { + s.doc().unwrap().doc.clone() +} + +/// The move [`DocState::moved`] names, when it took `from` to the document now. +fn moved_from(s: &Session, from: &Arc) -> Option { + let st = s.doc().unwrap(); + let m = st.moved.as_ref()?; + (m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by) +} + +// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the +// document the drag began with. +#[test] +fn a_move_of_whole_objects_names_the_documents_and_the_distance() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a, b]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap(); + assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move"); + let before = doc(&s); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge"); + + let start = doc(&s); + s.begin_interaction("Move").unwrap(); + for dx in [3.0, 7.5] { + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap(); + assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}"); + } +} + +// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move +// of part of what the selection shows name no move. +#[test] +fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a, b]); + let cases = [ + ("object.move", json!({"dx": 12, "dy": 0, "copy": true})), + ("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})), + ("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})), + ("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})), + ("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})), + ]; + for (cmd, p) in cases { + select(&mut s, &[a, b]); + let before = doc(&s); + s.execute(cmd, &p).unwrap(); + assert_eq!(moved_from(&s, &before), None, "{cmd} {p}"); + } +} + +// The key object is shown too: a move that leaves it where it was names no move. +#[test] +fn a_key_object_left_where_it_was_names_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a]); + s.active_mut().unwrap().selection.key = Some(b); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None); +} + +// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel +// grid snaps after the edit: neither is the object before the move moved by its distance. +#[test] +fn objects_that_snap_to_the_pixel_grid_name_no_move() { + let mut s = session(); + let a = rect(&mut s, 20.0); + select(&mut s, &[a]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path"); + + let mut s = session(); + let art = rect(&mut s, 20.0); + let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap(); + select(&mut s, &[id_of(&made)]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid"); +} + +// A member of a blend moved on its own changes the blend's spine. +#[test] +fn a_member_of_a_blend_names_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0)); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap(); + select(&mut s, &[a]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None); +} diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..252488b0ca 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -631,13 +631,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 +706,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 +734,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 +745,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 +796,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 +840,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 +851,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 +889,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 +984,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 +991,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 +1009,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 +1021,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 +1047,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 +1078,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 +1102,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 +1131,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 +1152,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/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/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/plugins.rs b/crates/engine/src/tests/plugins.rs index 4ecff31b3b..836daf8b05 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2256,6 +2256,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, }; 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/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb333e91d8..840d63e76e 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, @@ -940,7 +970,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 +1006,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}"); } } @@ -1352,6 +1398,18 @@ fn a_document_preset_is_an_instance_of_its_class() { assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); } +/// 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 /// the one before it. #[test] @@ -1529,6 +1587,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 +1643,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 +1682,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 +1705,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 +1807,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 +1823,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 +2090,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 +2205,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 +2427,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 +2445,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 +2495,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_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); +} + +/// Bad arguments throw before anything is written or opened. +#[test] +fn bad_arguments_are_refused_with_an_error() { + let base = folder("bad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let f = format!("new File({})", quoted(&dir.join("x.svg"))); + let huge = "a".repeat(5000); + let cases: Vec<(String, &str)> = 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/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..dfc603dc59 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -157,6 +157,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/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/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 0221d804ee..e26abfef2e 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})), 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/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/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 99% rename from crates/engine/tests/preflight.rs rename to crates/engine/tests/it/preflight.rs index e656596d71..73f6066bd3 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}; 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..1b2e879c3a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,12 +39,17 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), + ("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 +96,8 @@ 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 redo redraw selection selection= selectTool textFonts \ + toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=", ), ("DocumentPreset.", "prototype"), ( @@ -103,18 +108,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 +189,58 @@ 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"), ( "", "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ @@ -314,10 +371,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/native/plan.rs b/crates/eps/src/import/native/plan.rs index 6d4799721e..a23e8ea324 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -338,32 +338,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 diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 2d8d270cc7..28faccac69 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8663,3 +8663,35 @@ 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:?}"); } + +/// 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/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/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..308188daea 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -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..517caa9c06 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 @@ -690,6 +713,7 @@ impl Interp { can_wait: Rc::default(), waiting: false, waiting_hosted: false, + answer_throws: false, constructing: false, resuming: None, again: None, @@ -1031,6 +1055,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 +3589,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 +3597,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/realm.rs b/crates/js/src/realm.rs index 439b231d16..d673c92d26 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -380,6 +380,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 +427,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 +568,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 +588,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/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..2c8f54eb6e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,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", @@ -1531,7 +1531,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.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|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, `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 +1549,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", 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/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/realtext.rs b/crates/pdf/src/tests/realtext.rs index 7d1ac97027..7fcd06dd56 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -801,7 +801,7 @@ fn digits_unnamed(text: &str) -> Vec { out } -/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font +/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing `\u{FFFD}`. This subset font /// has no character map of its own, but the font is installed: each digit is found by its outline /// there, so the whole text stays one type object, with no outlines left behind. #[test] 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/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b7156550c8..a88d7fd04e 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 { @@ -472,6 +531,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 +568,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 +619,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 +643,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 +725,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 +739,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 +829,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,9 +852,11 @@ 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]]; } @@ -859,6 +953,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 +963,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 +1087,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 +1122,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 +1179,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 +1240,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); @@ -1267,6 +1373,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 +1397,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 +1438,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 +1459,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 +1752,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..ac0e69b52f 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())); @@ -288,13 +308,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `(` 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)`: a document method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + && catalog::DOM_FILE_WRITES.contains(&method.as_str()) + && !Self::defines(self.index_receiver, &method) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -320,7 +341,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if (file && catalog::FILE_WRITES.contains(&n)) || 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)) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { @@ -343,6 +366,87 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// 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 +469,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..4f536c9cb6 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,7 +77,13 @@ 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"]; + +// 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 +208,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/tests.rs b/crates/scriptcheck/src/tests.rs index 44255738ea..fb9553bcf4 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,408 @@ 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][..])]); +} + +/// `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 +2011,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] 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/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/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..0bcd5999b7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -363,6 +363,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 +540,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. diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..a4046e3fe7 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -892,11 +892,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 +938,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/text/web-fonts.txt b/crates/text/web-fonts.txt index 235ba98e13..d46cfe41c5 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -8,35 +8,5 @@ startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular startup | Noto Sans Georgian | Regular -background | Cairo | Regular -background | Tajawal | ExtraLight -background | Tajawal | Light -background | Tajawal | Regular -background | Tajawal | Medium -background | Tajawal | Bold -background | Tajawal | ExtraBold -background | Tajawal | Black -background | Almarai | Light -background | Almarai | Regular -background | Almarai | Bold -background | Almarai | ExtraBold -background | IBM Plex Sans Arabic | Thin -background | IBM Plex Sans Arabic | ExtraLight -background | IBM Plex Sans Arabic | Light -background | IBM Plex Sans Arabic | Regular -background | IBM Plex Sans Arabic | Medium -background | IBM Plex Sans Arabic | SemiBold -background | IBM Plex Sans Arabic | Bold -background | Noto Kufi Arabic | Regular -background | Amiri | Regular -background | Amiri | Italic -background | Amiri | Bold -background | Amiri | Bold Italic -background | Alexandria | Regular -background | Fustat | Regular -background | Reem Kufi | Regular -background | Aref Ruqaa | Regular -background | Aref Ruqaa | Bold -background | Gulzar | Regular demand | NanumGothic | Regular demand | Noto Sans Devanagari | Regular 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/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/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/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/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/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/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/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..a1c9dcf5b8 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| { @@ -108,6 +110,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option color::legend::open, color::nearest::COMMAND => color::nearest::open, select::COMMAND => select::open, + select::points_only::COMMAND => select::points_only::open, _ => return super::arrange::open(app, id), }; Some(open(app)) @@ -132,6 +135,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 +143,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 +167,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/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 76b3627f76..5ddeee621b 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -40,8 +40,8 @@ fn params(fields: &DialogFields) -> Value { /// 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); + // 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([ ("radius", FieldValue::Number(RADIUS)), ("constantGap", FieldValue::Bool(false)), @@ -72,6 +72,24 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { }) } +/// 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 { use serde_json::{Value, json}; @@ -158,6 +176,36 @@ mod tests { assert_eq!(geometry(&panel.app()), original); } + #[test] + fn reach_counts_the_circles_inside_a_selected_group() { + use crate::tests::panel_harness::Panel; + + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = bridge_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(), super::COMMAND, 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 = bridge_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(); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); + } + #[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())); @@ -180,4 +228,27 @@ mod tests { 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_an_ellipse_is_refused() { + use crate::tests::panel_harness::Panel; + + 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 = panel.app().session.doc().unwrap().history.undo.len(); + menus::invoke(&mut panel.app(), super::COMMAND, 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!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step"); + } } 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/app.rs b/crates/ui-egui/src/app.rs index 84ab44d769..0fda79c6d1 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}; @@ -139,6 +139,8 @@ impl VectorcraftApp { spelling: Default::default(), text_nodes: Default::default(), momentary: None, + hand: None, + zoom_tool: None, selection_box: None, selection_bounds: None, selection_marks: None, @@ -379,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); } @@ -716,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); @@ -805,8 +818,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. @@ -823,6 +837,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..1452288749 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); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 7f0ade064e..06c564f4c8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -81,6 +81,9 @@ pub struct CanvasCache { /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between /// 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 f340f3bac2..08f859b025 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -278,8 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the -/// picture last. +/// 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 { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; @@ -299,11 +299,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - widgets::show_hollow_corners(app, ui, space, kind); - // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this - // frame's pointer event, from the document as the event leaves it. + // The hollow Live Corners, the selection's marks, and the bounding box, Live Corners and shape widgets paint here + // in that order, under the 3D handles and the bars. All of them are display only and are drawn after the tool host + // has taken this frame's pointer event, from the document as the event leaves it. + let hollow = PaintSlot::reserve(ui.painter()); let marks = PaintSlot::reserve(ui.painter()); - widgets::show(app, ui, space, win, kind); + let shown_widgets = PaintSlot::reserve(ui.painter()); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); } @@ -339,14 +340,21 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } - let after = PaintSlot::reserve(ui.painter()); - selection::show(app, ui, space, win, kind); - marks.extend(ui.ctx(), after.take_after(ui.ctx())); + paint_into(ui, hollow, |ui| widgets::show_hollow_corners(app, ui, space, kind)); + paint_into(ui, marks, |ui| selection::show(app, ui, space, win, kind)); + paint_into(ui, shown_widgets, |ui| widgets::show(app, ui, space, win, kind)); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out } +/// Runs `draw` now and moves the shapes it paints on `ui`'s layer to `slot`, their place in the paint order. +fn paint_into(ui: &mut Ui, slot: PaintSlot, draw: impl FnOnce(&mut Ui)) { + let after = PaintSlot::reserve(ui.painter()); + draw(ui); + slot.extend(ui.ctx(), after.take_after(ui.ctx())); +} + /// The keys held now, as the engine's tools read them, with `space` set while Space is down. pub(crate) fn held_mods(ctx: &egui::Context) -> vectorcraft_tools::Mods { let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space))); 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..662f46db4a 100644 --- a/crates/ui-egui/src/canvas/artboards/tests.rs +++ b/crates/ui-egui/src/canvas/artboards/tests.rs @@ -47,13 +47,13 @@ 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())); + assert!(frames_of(&app, true).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())); 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/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index d1f8c469a8..56ecf1b24c 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -35,7 +35,8 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, let options = super::selection::path_options(&app.session.prefs); let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app); let lists = [extra, overlays]; - for (i, o) in extra.iter().chain(overlays).enumerate() { + // Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none. + for (i, o) in extra.iter().chain(overlays).enumerate().filter(|(_, o)| is_control(o)) { ui.push_id(("tool-control", i), |ui| show_control(ui, rect, o)); } for (i, list) in lists.into_iter().enumerate() { @@ -48,6 +49,26 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, }); } +/// Whether `o` is shown as a framework control of its own ([`show_control`]) rather than painted by [`ToolMarks`]. +fn is_control(o: &Overlay) -> bool { + match o { + Overlay::Marquee(_) | Overlay::SelectionMarquee { .. } | Overlay::SharedPath { .. } | Overlay::Outlines { .. } | Overlay::Distance { .. } => { + true + } + Overlay::Path { .. } + | Overlay::Line { .. } + | Overlay::Anchor { .. } + | Overlay::CurvePoint { .. } + | Overlay::Handle { .. } + | Overlay::Label { .. } + | Overlay::Measure { .. } + | Overlay::Highlight { .. } + | Overlay::Swatch { .. } + | Overlay::GridLine { .. } + | Overlay::HoverText { .. } => false, + } +} + /// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance. fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) { match o { diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index e0ac7e7aee..4f50576df8 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::collections::hash_map::{DefaultHasher, Entry}; use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Weak}; use craft::behavior::Input; use craft::behavior::Metrics; @@ -18,9 +19,9 @@ use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline}; use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, NodeId, NodeKind}; use vectorcraft_engine::{DocState, Prefs, ViewInfo}; -use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; +use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point, Vec2}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; @@ -28,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; @@ -59,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. @@ -258,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, @@ -278,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 }; @@ -294,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))); } @@ -325,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 } @@ -632,9 +660,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect); } let key = marks_key(app, st, tool, tool_points); + let view = view_key(app, st, tool, tool_points); let marks = match app.canvas.selection_marks.take() { Some(kept) if kept.key == key => kept, - _ => SelectionMarks::build(app, st, tool, tool_points, key), + Some(kept) if kept.view == view && kept.selection == st.selection => { + kept.follow(st, key).unwrap_or_else(|| SelectionMarks::build(app, st, tool, tool_points, (key, view))) + } + _ => SelectionMarks::build(app, st, tool, tool_points, (key, view)), }; for o in &marks.outlines { let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision); @@ -655,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); @@ -663,29 +704,99 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } /// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with -/// nothing changed walks no selected object. +/// nothing changed walks no selected object. They are also kept while the document and the selection stay the same +/// under another revision, and moved with the selection when a move ([`vectorcraft_engine::Moved`]) took the document +/// they show to the one now. pub(crate) struct SelectionMarks { key: u64, + /// [`view_key`] of the state they were made for. + view: u64, + /// The selection they show. + selection: vectorcraft_doc::Selection, + /// The document they show. + doc: Weak, + /// A document they show moved by a distance: the one they were built for and no distance, or the document the + /// last move they followed started from and its distance. Each step of a drag starts from the document the drag + /// began with ([`SelectionMarks::follow`]). + from: (Weak, Vec2), outlines: Vec, anchors: Anchors, dots: Dots, } impl SelectionMarks { - fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self { + fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, (key, view): (u64, u64)) -> Self { #[cfg(test)] tests::MARKS_BUILT.with(|built| built.set(built.get() + 1)); - Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) } + let doc = Arc::downgrade(&st.doc); + Self { + key, + view, + selection: st.selection.clone(), + from: (doc.clone(), Vec2::ZERO), + doc, + outlines: outlines(app, st), + anchors: anchors(app, st, tool, tool_points), + dots: dots(app, st), + } + } + + /// The marks of `st`, whose [`marks_key`] is `key`, from these marks of the same selection and view: these marks + /// when `st` shows the same document, these marks moved by `st`'s move when it took the document they show, or the + /// document of [`SelectionMarks::from`], to the one `st` shows, else `None`. + fn follow(mut self, st: &DocState, key: u64) -> Option { + let now = Arc::as_ptr(&st.doc); + if self.doc.as_ptr() != now { + let moved = st.moved.as_ref().filter(|m| m.to.as_ptr() == now && m.selection == st.selection)?; + let by = if moved.from.ptr_eq(&self.doc) { + moved.by + } else if moved.from.ptr_eq(&self.from.0) { + moved.by - self.from.1 + } else { + return None; + }; + self.translate(by); + self.from = (moved.from.clone(), moved.by); + self.doc = moved.to.clone(); + } + self.key = key; + Some(self) + } + + /// Moves every mark by `by`. + fn translate(&mut self, by: Vec2) { + let shift = vectorcraft_geom::Affine::translate(by); + for o in &mut self.outlines { + 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().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; + } + let dots = &mut self.dots; + for (at, _) in dots.origins.iter_mut().chain(&mut dots.centers).chain(&mut dots.key_anchor) { + *at += by; + } } } -/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the -/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the -/// Selection & Anchor Display preferences. +/// What the selection's marks are built from: the document and its selection (its uid and revision), and what +/// [`view_key`] hashes. fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 { + let mut h = DefaultHasher::new(); + (st.revision, view_key(app, st, tool, tool_points)).hash(&mut h); + h.finish() +} + +/// What the selection's marks are built from besides the document's content and the selection: the document (its +/// uid), the parts the view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, +/// and the Selection & Anchor Display preferences. +fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 { let mut h = DefaultHasher::new(); let hides = ViewHides::of(app); - (st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h); + (st.uid, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h); let prefs = &app.session.prefs; (prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h); h.finish() diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 672b07094a..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,80 @@ 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"); } + +/// Every point of the outlines, the anchors and their handles, and the dots, in order. +fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec { + let mut out = vec![]; + for path in outlines.iter().flat_map(|o| o.paths.iter().chain(&o.key)) { + for el in path.elements() { + match *el { + PathEl::MoveTo(a) | PathEl::LineTo(a) => out.push(a), + PathEl::QuadTo(a, b) => out.extend([a, b]), + PathEl::CurveTo(a, b, c) => out.extend([a, b, c]), + PathEl::ClosePath => {} + } + } + } + for knot in anchors.paths.iter().chain(&anchors.plain).flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) { + out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]); + } + out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at)); + out +} + +/// Whether the marks the canvas keeps are, to rounding, the ones the builders give for the state now. +fn kept_marks_are_current(app: &VectorcraftApp) -> bool { + let kept = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); + let st = app.session.active().unwrap(); + let now = points_of(&outlines(app, st), &anchors(app, st, app.session.tool_id(), false), &dots(app, st)); + let was = points_of(&kept.outlines, &kept.anchors, &kept.dots); + now.len() == was.len() && now.iter().zip(&was).all(|(a, b)| (*a - *b).hypot() < 1e-9) +} + +// Whole-app frames keep the selection's marks through a new revision of the same document and selection, and move +// them with a move of the selection instead of building them: a move command, each step of a drag, and the drag's end +// build nothing and keep the marks of the state now. A scale and an undo still build them once. +#[test] +fn a_move_of_the_selection_moves_its_marks_without_building_them() { + let (mut app, _) = scene(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MARKS_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }); + } + MARKS_BUILT.with(std::cell::Cell::get) - before + }; + frames(&mut app, 3); + let layer = app.session.active().unwrap().doc.layers[0].id; + let revision = app.session.active().unwrap().revision; + app.run("layer.setCurrent", json!({"id": layer.0})).unwrap(); + assert_ne!(app.session.active().unwrap().revision, revision, "a new revision"); + assert_eq!(frames(&mut app, 3), 0, "a new revision of the same document and selection"); + app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap(); + assert_eq!(frames(&mut app, 3), 0, "a move command"); + assert!(kept_marks_are_current(&app), "after a move command"); + + app.session.begin_interaction("Move").unwrap(); + for dx in [3.0, 7.5, -2.0] { + app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 4], "copy": false})).unwrap(); + assert_eq!(frames(&mut app, 2), 0, "a drag's step by {dx}"); + assert!(kept_marks_are_current(&app), "after a drag's step by {dx}"); + } + app.session.commit_interaction().unwrap(); + assert_eq!(frames(&mut app, 2), 0, "the drag's end"); + assert!(kept_marks_are_current(&app), "after the drag"); + + app.run("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})).unwrap(); + assert_eq!(frames(&mut app, 3), 1, "a scale"); + assert!(kept_marks_are_current(&app), "after a scale"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frames(&mut app, 3), 1, "an undo"); + assert!(kept_marks_are_current(&app), "after an undo"); +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a5fa556b8c..41d0e93837 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -303,7 +303,22 @@ fn press(at: Pos2, pressed: bool) -> egui::Event { /// object has after that frame's event, and none at the corner it had before it. #[test] fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + selection_drag_marks_follow(drag_app()); +} + +/// With Show Bounding Box While Moving and Drawing on, a Selection tool drag draws the bounding box and its handles in +/// the frame the pointer moves: at the corner the object has after that frame's event, and none at the corner it had +/// before it. +#[test] +fn a_selection_drag_draws_its_bounding_box_in_the_frame_the_pointer_moves() { let mut app = drag_app(); + app.session.prefs.bounding_box_while_moving_and_drawing = true; + selection_drag_marks_follow(app); +} + +/// Drags a selected rectangle with the Selection tool in six frames and checks each frame that moved it: a mark at +/// its corner after the frame's event, none at its corner before. +fn selection_drag_marks_follow(mut app: VectorcraftApp) { let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); app.select_tool("selection"); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); @@ -411,6 +426,23 @@ fn a_click_activates_its_artboard_and_paste_in_place_goes_onto_it() { assert_eq!((b.x0, b.y0), (boards[2].x0 + 10.0, boards[2].y0 + 15.0)); } +/// Copy uses the active board as its origin even when selected art lies on a different board. +#[test] +fn copy_and_paste_use_the_active_source_and_destination_artboards() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + let boards: 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. @@ -865,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] @@ -4859,6 +4943,25 @@ fn a_flip_during_a_press_waits_for_the_release() { assert_eq!(app.session.tool_id(), "eraser", "the frame after the release"); } +/// A selected Hand tracks its drag in the framework, outside the document tool's grab. +#[test] +fn turning_the_pen_during_a_hand_drag_waits_for_release() { + let (mut app, stylus, ctx) = pen_app(); + app.select_tool("hand"); + let at = app.canvas_view().unwrap().rect.center(); + let to = at + egui::vec2(30.0, 20.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + stylus.set(tip(0.5)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + stylus.set(eraser_end(0.5)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert_eq!(app.session.tool_id(), "hand"); + frame(&mut app, &ctx, vec![button(to, false)]); + assert_eq!(app.session.tool_id(), "hand"); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.tool_id(), "eraser"); +} + /// #764: a tool chosen while the eraser end stands in (the toolbar and shortcuts call /// `select_tool`; menus and MCP run `tool.select`) stays when the tip comes back. #[test] diff --git a/crates/ui-egui/src/canvas/tests_edge_scroll.rs b/crates/ui-egui/src/canvas/tests_edge_scroll.rs index 79c09b3291..3a67ee6840 100644 --- a/crates/ui-egui/src/canvas/tests_edge_scroll.rs +++ b/crates/ui-egui/src/canvas/tests_edge_scroll.rs @@ -127,13 +127,69 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() { let (mut app, ctx, _) = zoomed_in("hand"); let rect = app.canvas_view().unwrap().rect; let start = rect.center(); + let before = center(&app); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); let edge = pos2(rect.right() - 4.0, start.y); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); let c0 = center(&app); + assert!(c0.x < before.x, "dragging the selected Hand right must pan the view"); for _ in 0..3 { frame(&mut app, &ctx, vec![]); } 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/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index cc62cc3fe6..2e33ef9cf8 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -590,7 +590,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 { @@ -629,6 +631,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too // the release, and a pointer over another window for the pointer to come in. if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() + && !ToolHost::in_gesture(ui.ctx(), pass.id) && ui.input(|i| i.pointer.has_pointer()) && crate::stylus::sync_eraser_tool(app) { @@ -650,7 +653,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 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 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); + } + 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/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 67cc29b63f..0a9e079f68 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -548,6 +548,34 @@ fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() { } } +/// 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.starting("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/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/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/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/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index c20582141e..b9a4a47b6e 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, } @@ -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}")); } } @@ -1127,21 +1137,35 @@ mod tests { open(&mut app); let out = laid_out(&mut app); let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); - 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(|l| !l.is_empty()) && 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))) - .expect("a preset card that is not selected"); + .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 @@ -1413,11 +1437,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); 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/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/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/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/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/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/dock.rs b/crates/ui-egui/src/dock.rs index fdaaebcee1..dcff2191a4 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,28 @@ 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" + | "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/font_menu.rs b/crates/ui-egui/src/font_menu.rs index bc7d206428..21c19bdd03 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -114,7 +114,7 @@ pub(crate) fn family_picker<'a>( .filters(filters) .sets(sets) .scripts(&FontScript::ALL) - .filter_layout(FilterLayout::Chips) + .filter_layout(FilterLayout::Toolbar) } /// What one pass of a picker reads of the app, for a host that has no `app` while it draws (a dialog). 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/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/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/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/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..5681df62bf 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,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", @@ -1532,7 +1532,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.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|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, `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 +1550,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", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6deacc0c01..017486e7ad 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 { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2ebca9a8bc..2d1ea7cfb9 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -681,13 +681,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 +1130,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/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index bff0bd1d4d..ca9547889f 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -158,7 +158,7 @@ pub(crate) fn step_place(step: usize, in_batch: Option) -> String { } } -/// `text` as a status message shows it: control characters become `�`, and text past 80 +/// `text` as a status message shows it: control characters become `\u{FFFD}`, and text past 80 /// characters ends in `…`. pub(crate) fn shown_text(text: &str) -> String { const MAX: usize = 80; diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index 1fe2f13711..208c293b70 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(); 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/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/character.rs b/crates/ui-egui/src/panels/character.rs index bfcb770b7e..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,19 +1225,17 @@ 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::Chips); + .filter_layout(FilterLayout::Toolbar); if let Some(text) = &sample { source = source.preview_text(text); } @@ -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/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_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 e6f7cb6e86..5cb45f666a 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -59,6 +59,12 @@ pub(crate) fn copy_value(ui: &mut Ui, label: &str, value: &str, mono: bool) -> b /// The same guarded full-value copy for an already shown readout. An elided path remains /// static text: selection indices must describe the text actually shown by the framework. pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bool { + // A container's measuring run shows the readout in an invisible sizing pass before the frame's real run, with the + // same id and the same input. It neither copies nor reads or clears the remembered press: clearing it there would + // leave the real run's release without its press. + if ui.is_sizing_pass() { + return false; + } // The click's own position and keys: a move or a key change after the release in the same // frame leaves the pointer and the held keys elsewhere. A frame with more than one release // copies nothing, since the click flags below do not say which release they describe. diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 2987d350a8..347a22ae83 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -182,8 +182,9 @@ pub struct LayersUi { /// The selection square clicked last in each open document, by the document's `uid`: where a Shift-click on another /// square starts. pub art_anchors: HashMap, - /// The active document's rows with the [`LayerRows::key`] they were listed at. - rows: Option<(u64, Tracked)>, + /// The active document's rows with the [`LayerRows::key`] they were listed at and the document's `uid` and + /// `reverts`. + rows: Option<(u64, (u64, u64), Tracked)>, } impl Default for LayersUi { @@ -223,7 +224,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { thumbnails.hold(app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy()); let settings = app.ui.layers_panel.settings(); refresh_rows(app); - let (Some(st), Some((_, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return }; + let (Some(st), Some((_, _, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return }; let tree = DocLayers::of(st, kept); let source = thumbs::LayerThumbs { doc: &st.doc }; let mut panel = LayersPanel::new(kept) @@ -294,13 +295,23 @@ fn unrevealed(app: &mut VectorcraftApp, f: impl FnOnce(&mut VectorcraftApp) - r } -/// Lists the active document's rows again when what they are listed from changed. +/// Lists the active document's rows again when what they are listed from changed. The new rows go into the kept +/// [`Tracked`] while the document is the same, so the panel keeps its display order when the +/// [order revision](LayerRows::order_of) stays; another document, or the same one after File › Revert, gets a new one. fn refresh_rows(app: &mut VectorcraftApp) { let Some(st) = app.session.active() else { return }; let key = LayerRows::key(app, st); - if app.ui.layers_ui.rows.as_ref().is_none_or(|(kept, _)| *kept != key) { - let rows = Tracked::new(LayerRows::new(app, st)); - app.ui.layers_ui.rows = Some((key, rows)); + let doc = (st.uid, st.reverts); + if app.ui.layers_ui.rows.as_ref().is_some_and(|(kept, _, _)| *kept == key) { + return; + } + let new = LayerRows::new(app, st); + match &mut app.ui.layers_ui.rows { + Some((kept, of, rows)) if *of == doc => { + rows.edit(|rows| *rows = new); + *kept = key; + } + slot => *slot = Some((key, doc, Tracked::new(new))), } } 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/model.rs b/crates/ui-egui/src/panels/layers/model.rs index c73794b6d0..ecd2d7a954 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -202,6 +202,14 @@ pub(super) struct LayerRows { /// In isolation mode, the isolated node: the top row. #[plain_data(assume = "a node id is an integer")] root: Option, + /// What the display order is built from ([`LayerRows::order_of`]). + order: u64, +} + +#[cfg(test)] +thread_local! { + /// How many times [`LayerRows::children`] was asked on this thread. + pub(super) static CHILDREN_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`LayerRows`] with the editing state of their document, for the panel's host code in one pass. @@ -243,7 +251,9 @@ impl LayerRows { let guide_rows = ruler.iter().enumerate().filter_map(|(i, g)| Some((g.id?, i))).collect(); let blends = st.selection.objects.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }))); let selected: HashSet = st.selection.objects.iter().copied().collect(); + let root = st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id); Self { + order: Self::order_of(doc, &st.layers_open, app.ui.layers_panel.layers_only, root), doc: doc.clone(), opts: app.ui.layers_panel.clone(), xml_id: by_xml_id(app), @@ -258,10 +268,20 @@ impl LayerRows { holding: super::rows::holding(doc, &selected), selected, blends: blends.collect(), - root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id), + root, } } + /// A hash of everything the display order reads ([`LayerTree::children`] and [`LayerTree::is_open`]): the + /// document, which an edit replaces and a selection change keeps (its ruler guides and an opacity mask being + /// edited are in it), the open rows, Show Layers Only and the isolated node. The selection, the highlighted rows, + /// the current layer, the names and the other Panel Options are not in it. + fn order_of(doc: &Arc, open: &OpenRows, layers_only: bool, root: Option) -> u64 { + let mut hasher = DefaultHasher::new(); + (Arc::as_ptr(doc) as usize, open.generation(), layers_only, root).hash(&mut hasher); + hasher.finish() + } + /// What the rows of `st` are listed from: the document and its revision (which every edit and /// selection change moves), the open rows, isolation mode, the highlighted rows and the current /// layer, the Panel Options, Identify Objects By and the language. @@ -461,6 +481,8 @@ impl LayerTree for LayerRows { /// The top rows are the layers (only the opacity mask's while one is edited), or in isolation /// mode the isolated layer, sublayer, group or object. fn children(&self, parent: Option<&RowId>) -> Vec { + #[cfg(test)] + CHILDREN_CALLS.with(|c| c.set(c.get() + 1)); match parent { None => match self.root { Some(root) => vec![RowId::Node(root)], @@ -491,6 +513,11 @@ impl LayerTree for LayerRows { false } + /// The display order changes only with what [`LayerRows::order_of`] hashes: a selection change keeps it. + fn order_revision(&self) -> Option { + Some(self.order) + } + fn info(&self, id: &RowId) -> LayerInfo { match *id { RowId::Node(id) => match self.doc.node(id) { 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 5eeca21a8e..6155d4f6e7 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]). @@ -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] @@ -1352,3 +1496,78 @@ fn idle_frames_walk_no_node_for_the_selection_squares() { } assert!((1..=12).contains(&(visits() - before)), "a new selection walks the tree once: {}", visits() - before); } + +/// A selection change keeps the panel's display order: no row is asked for the rows inside it. Closing a row, Show +/// Layers Only and an edit build the order again, and the rows follow. +#[test] +fn a_selection_change_keeps_the_display_order() { + use crate::tests::panel_harness::Panel; + let calls = || super::model::CHILDREN_CALLS.with(std::cell::Cell::get); + let (mut app, [_, sub, _, b, a, c]) = nested(); + for (id, name) in [(sub, "Sub"), (b, "B"), (a, "A"), (c, "C")] { + name_row(&mut app, id, name); + } + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let mut panel = Panel::new(app, show); + panel.frame(); + let before = calls(); + panel.app().session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for _ in 0..3 { + panel.frame(); + } + assert_eq!(calls() - before, 0, "a selection change asks no row for its rows"); + assert!(panel.shows("A") && panel.shows("B"), "the rows stay"); + + expand(&mut panel.app(), &json!({"ids": [sub.0], "open": false})).unwrap(); + let before = calls(); + panel.frame(); + panel.frame(); + assert!(calls() > before, "closing a row builds the order again"); + assert!(!panel.shows("A") && panel.shows("Sub") && panel.shows("C"), "the closed sublayer's rows are gone"); + + panel.app().ui.layers_panel.layers_only = true; + panel.frame(); + panel.frame(); + assert!(!panel.shows("C") && panel.shows("Sub"), "Show Layers Only leaves the objects out"); + + panel.app().ui.layers_panel.layers_only = false; + panel.app().session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + panel.frame(); + panel.frame(); + assert!(panel.shows("Sub") && !panel.shows("C"), "isolation mode lists only the isolated sublayer"); + panel.app().session.execute("object.exitIsolation", &json!({})).unwrap(); + expand(&mut panel.app(), &json!({"ids": [sub.0], "open": true})).unwrap(); + let made = panel.app().session.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap(); + let d = NodeId(made["id"].as_u64().unwrap()); + name_row(&mut panel.app(), d, "D"); + panel.frame(); + panel.frame(); + assert!(panel.shows("D") && panel.shows("C"), "an edit lists the new object"); +} + +/// The order revision stays through a selection change and moves with the document, the open rows, Show Layers Only +/// and isolation mode. +#[test] +fn the_order_revision_follows_what_the_display_order_reads() { + let order = |app: &VectorcraftApp| LayerRows::new(app, app.session.active().unwrap()).order_revision(); + let (mut app, [_, sub, g, b, a, _]) = nested(); + let first = order(&app); + assert!(first.is_some(), "the rows report an order revision"); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(order(&app), first, "a selection change keeps it"); + app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap(); + let isolated = order(&app); + assert_ne!(isolated, first, "isolation mode moves it"); + app.session.execute("object.exitIsolation", &json!({})).unwrap(); + let left = order(&app); + assert_ne!(left, isolated, "leaving isolation mode moves it"); + app.ui.layers_panel.layers_only = true; + assert_ne!(order(&app), left, "Show Layers Only moves it"); + app.ui.layers_panel.layers_only = false; + assert_eq!(order(&app), left, "and turning it off gives it back"); + expand(&mut app, &json!({"ids": [g.0], "open": false})).unwrap(); + let closed = order(&app); + assert_ne!(closed, left, "closing a row moves it"); + name_row(&mut app, a, "A"); + assert_ne!(order(&app), closed, "an edit moves it"); +} 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/properties.rs b/crates/ui-egui/src/panels/properties.rs index 7e3caa1a43..70973df597 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,8 @@ 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 key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -63,7 +65,9 @@ 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 changed = app.ui.properties_panel.content.replace(content) != Some(content); + 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 +81,33 @@ 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 { + let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections); + } + panel.show(ui, sections); +} + +/// What the sections show: the document and its revision, 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.revision, 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 @@ -291,8 +321,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,8 +332,7 @@ 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 } 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..96e9fc2cb0 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -130,6 +130,66 @@ 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}"); + } + } +} + /// 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 +1144,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(); 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/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index f20c725ac0..7e17c305a5 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1623,3 +1623,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/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_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_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/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/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..d22d8e9eb6 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() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5ac49daeb9..eeef403f06 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -490,6 +490,15 @@ pub struct ContextSpelling { pub suggestions: Vec, } +/// The main window as saved in the UI preferences through 0.24.1. Positions are desktop pixels. +#[derive(Clone, Copy, Debug, Deserialize)] +pub struct LegacyWindow { + pub pos: Option<[i32; 2]>, + pub size: [f32; 2], + #[serde(default)] + pub maximized: bool, +} + /// Two states are equal when they save the same: the settings store writes only a changed saved form, /// and the panels' session state is no change to save. #[derive(Clone, Debug, Serialize, Deserialize)] @@ -500,6 +509,9 @@ pub struct UiState { /// it is never written back. #[serde(rename = "language", skip_serializing)] pub legacy_language: Option, + /// Used until the shared window store has recorded the main window. + #[serde(rename = "window", skip_serializing)] + pub legacy_window: Option, pub brightness: Brightness, /// The panel arrangement: docks, floating windows, closed panels and where each goes back. One /// `Arc` the dock area keeps across frames; writers change it through `Arc::make_mut`. @@ -1448,6 +1460,7 @@ impl Default for UiState { fn default() -> Self { Self { legacy_language: None, + legacy_window: None, brightness: Brightness::MediumDark, dock_workspace: std::sync::Arc::new(crate::panel_docking::default_workspace(&[])), tools_last_used: Default::default(), 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/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 f1f6bcd09c..41b5264479 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -355,10 +355,11 @@ fn a_control_port_cancel_of_a_dialog_preview_reads_the_menus() { } /// OK applies the rotation a dialog previews as one undo step: the menus are read then, with Undo -/// naming it, and not for the angles previewed before. +/// naming it, and not for the angles previewed before. Once the dialog's angle field no longer takes +/// the keys, the menus are sent once more without the text-editing gate. #[test] fn applying_a_dialog_preview_reads_the_menus() { - let (m, (read, synced, closed, after)) = undisturbed(|m| { + let (m, (read, synced, applied, closed, after)) = undisturbed(|m| { m.rotate_preview(); let read = m.angles(4); let synced = m.fake.synced(); @@ -367,12 +368,21 @@ fn applying_a_dialog_preview_reads_the_menus() { // gone two frames later. m.frame(vec![]); m.frame(vec![]); + let applied = m.fake.synced(); + // The frame after the field gives up the keys sets the gate. + for _ in 0..4 { + if !m.ctx.egui_wants_keyboard_input() { + break; + } + m.frame(vec![]); + } m.frame(vec![]); - (read, synced, !m.app.session.in_interaction() && !m.app.any_dialog_open(), m.fake.synced()) + (read, synced, applied, !m.app.session.in_interaction() && !m.app.any_dialog_open(), m.fake.synced()) }); assert_eq!(read, 0, "the menus weren't read while the dialog previewed the angles"); assert!(closed); - assert_eq!(after, synced + 1, "the menus were read"); + assert_eq!(applied, synced + 1, "the menus were read"); + assert_eq!(after, synced + 2, "and sent once more when the gate changed"); assert_eq!(find(&m.fake.last(), "edit.undo").label, "Undo Rotate"); } @@ -448,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..60e6bd2182 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); 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..6dc9853a2a 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,36 @@ 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}"); + 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/theme.rs b/crates/ui-egui/src/theme.rs index 1aa688ceb9..374fe2b460 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -166,10 +166,14 @@ const SIZES: &[u8] = br#"{ "size.page.button_side": 16, "size.page.link": 24 }, + "comfortable": { + "size.icon.lg": 26 + }, "compact": { "size.control.md": 26, "size.button": 24, "size.icon.glyph_md": 16, + "size.icon.lg": 24, "size.rail.width": 38, "size.dock.column": 310, "size.bar.column": 14, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 618bace39b..e80ed26a77 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -823,7 +823,7 @@ fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) { None => button, }; // Small in two columns, where the three sit side by side in the rail's width. - let button = if two { button.size(ControlSize::Sm) } else { button }; + let button = if two { button.size(ControlSize::Sm).glyphs(craft::ui::style::GlyphRole::Tool) } else { button }; button.show(ui).clicked() }; let mut run = None; 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..0e9daff967 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 @@ -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 @@ -768,8 +771,8 @@ 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 (`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. @@ -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..a1ceccaf59 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. @@ -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`) and `thread::sleep` in test code (`sleep`). 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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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 bdf38e3fe6..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 (+1 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (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 @@ -23,12 +23,12 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Convert to Shape | Rectangle, Rounded Rectangle, Ellipse | 3/3 | — | | Crop Marks | Crop Marks | 1/1 | — | | Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place; Twist's handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral without kinks where its pieces join (#7069, `twist_joins_its_pieces_smoothly`). | -| Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | +| Path | Offset Path, Outline Object, Outline Stroke | 3/3 | — | | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own; each of the other Pathfinder effects keeps its own Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, taken from Pathfinder Options when applied and edited in Pathfinder Options opened from its Appearance panel row ([Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html)) | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | -| Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | +| Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | — | | SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform. A blur or drop shadow that blurs more in one direction than another in the document (two different standard deviations, or one in a skewed or unevenly scaled user space) is kept as this effect rather than opened as an even Gaussian Blur or Drop Shadow | -| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | +| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers its resolution, PDF export warns once per object with the requested and the lowest achieved ppi diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a22db526d1..75f47d7a1c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -43,7 +43,7 @@ Paragraph reconstruction binds the source lines' validated carried faces before checking wrapping. The native-reopen regressions compare conflicting-glyph positions and wrapped paragraph ink bounds with outline imports, including filled-and-stroked `TJ` text. The focused engine PDF-fidelity, PDF file-font/stroked-text and text binding/shared-outline suites passed -56 tests on the canonical-main integration candidate. Full workspace CI and hardening paths +56 tests on the canonical-main integration candidate, and full workspace CI passed on #4569 before it merged. Hardening paths outside those suites remain pending. Existing PDF respacing and composite-font regressions remain; no parity score or estimate changes. @@ -55,13 +55,13 @@ from the public specifications, and users' own `.ai` files are used locally only ## Summary -Ordinary File > Save offers Save As when its own location refuses writes with a terminal permission/read-only error (#6146). The picker suggests the original filename and format, keeps the original options when the format is unchanged, and opens the chosen format’s Save options when it changes. It starts in Documents (home or host default if unavailable). Cancel leaves the document modified at its original path. Explicit Save As/Copy/export, recovery failures and Close/Quit keep their existing error dialog. Non-UI saves return `READ_ONLY_LOCATION: ` without opening a panel. Focused UI regressions passed; engine regression execution and native panel acceptance pending; format scores unchanged. +Ordinary File > Save offers Save As when its own location refuses writes with a terminal permission/read-only error (#6146). The picker suggests the original filename and format, keeps the original options when the format is unchanged, and opens the chosen format’s Save options when it changes. It starts in Documents (home or host default if unavailable). Cancel leaves the document modified at its original path. Explicit Save As/Copy/export, recovery failures and Close/Quit keep their existing error dialog. Non-UI saves return `READ_ONLY_LOCATION: ` without opening a panel. Focused UI and engine regressions passed (#6671); native panel acceptance pending; format scores unchanged. | | 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 +139,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 +338,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. @@ -425,6 +432,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. | diff --git a/docs/gaps.md b/docs/gaps.md index fd7e4a6b9f..205b6161be 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 , 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 , 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. @@ -13,7 +13,7 @@ > Outline Stroke is available in the canvas context menu when the selection has an outlinable stroke (#5267). Scores and estimates unchanged. -> **File-font hardening status (2026-11-12, #4569):** G8 implementation and synthetic regressions added; compilation and runtime proof pending. Scores and estimates unchanged. +> **File-font hardening status (2026-11-12, #4569):** G8 implementation and synthetic regressions added; #4569 merged with its CI gate passing. Scores and estimates unchanged. ## Feature submission evidence @@ -23,13 +23,15 @@ 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. - **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. @@ -172,7 +174,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). **Alpha blockers:** none. Every core workflow passes the [alpha gate](roadmap.md#alpha-gate); G9 is the only partial one, and it blocks beta, not alpha. -**To beta:** G1, G9, G10, G11, G12, the corpus and QA part of G8, the type-core part of G4, macOS pen pressure +**To beta:** G1, G9, G10, G11, G12, the corpus and QA part of G8, the type-core part of G4, native Wayland pen pressure from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall clock with 4–6 agents. ## G1 Interaction fidelity @@ -185,7 +187,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 +199,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. @@ -229,7 +231,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Artboard Options' 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)): per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`) that the canvas draws as a center cross and lines from the middle of each side through the center; exports and print leave them out. - **Done (#2849):** Artboard Options' video display options ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)): Show Video Safe Areas (`showVideoSafeAreas`) outlines the action-safe area 3.5% and the title-safe area 5% in from each edge, our choice from [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf) (the help page gives no numbers), on the canvas only; Video Ruler Pixel Aspect Ratio (`videoRulerPixelAspectRatio`, 0.1–10, default 1) is the width of one video pixel over its height. Both per artboard, one undo step, in the native format only when set. View › Rulers › Show Video Rulers is in G7. - **Done (#3705):** Draw Inside in isolation mode ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)): with the object drawn into isolated by a double-click, art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed; it used to stay locked and dimmed beside the isolated path, and double-clicks never reached the clip group. -- **Done:** Artboard Options' 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)): per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`) that the canvas draws as a center cross and lines from the middle of each side through the center; exports and print leave them out. Video safe areas, video rulers and the pixel aspect ratio remain missing. +- **Done:** Artboard Options' 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)): per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`) that the canvas draws as a center cross and lines from the middle of each side through the center; exports and print leave them out. - **Done:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Done (#2691):** a double-click on the Line Segment, Arc, Rectangular Grid or Polar Grid tool opens its Tool Options, as the [Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) pages (step 3) and the [Tools](https://helpx.adobe.com/illustrator/using/tools.html) page describe: the tool's click dialog without a place to draw (Line Segment adds Fill Line; the grids keep their Default Size and Reference Point). OK draws nothing and sets what the next drag draws with and what a click's dialog opens at; Cancel changes nothing. Editing a grid's rows and columns after it is drawn (the rest of #2691) remains. Broader G1 estimate unchanged. - **Done:** Simplify of part of a path, as the [manual-simplify page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) describes for part of a path picked with Direct Selection: with anchors or segments of a path direct-selected, Object › Path › Simplify (the slider, Auto-Simplify and the dialog) refits only each run of selected segments between its end anchors, which stay where they are with their outer handles; the other anchors and segments stay exactly as they were, a closed path's run may cross its start point, separate runs on one path simplify independently in one undo step, and the runs stay selected (`object.path.simplify` `wholePaths: true` simplifies such paths whole). Tests: `crates/engine/src/tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. Broader G1 estimate unchanged. @@ -257,9 +259,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done (#834):** bezier drag previews no longer freeze: a Pen, Anchor Point or Direct Selection drag gets every position the pointer is seen at, including the one where it comes back into the window after leaving it and a move in the frame it lets go, so the release commits where the pointer let go; a click's jitter stays a click. -- **Missing (noted for reporters, 2026-10-14):** aligning anchor points selected with - Direct Selection to a key anchor (from #1636: they align to their bounds; the current public Align page does - not say how the key anchor is chosen, so this waits for the owner). Inside the estimate below. +- **Done (#7769, #8023):** aligning anchor points selected with + Direct Selection to a key anchor (from #1636): with several anchors selected, a click on one of them without + modifiers makes it the key anchor that Align and Distribute keep in place. Inside the estimate below. - **Missing:** a tool-by-tool, panel-by-panel pass over modifiers, cursors, the Properties panel per context, isolation mode and small behaviours, against the public tool and shortcut documentation. Itemized in [ui-parity.md](ui-parity.md). The Shaper's construction-mode widget and gesture refinements remain. @@ -325,14 +327,14 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G10 Launch and stability on real machines -- **Unconfirmed (2026-10-14):** Tool cursors are painted into the window on Wayland (#1652; not run on Linux, #1645 stays open until confirmed). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). +- **Done (2026-10-14):** Tool cursors are painted into the window on Wayland (#1652; the reporter confirmed the size on Hyprland, and #1645 is closed). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; the reporter confirmed it on 0.11.0). - **Done:** RPM required dependencies use 64-bit library capabilities and declare glibc 2.35, libm and libgcc_s (#1275); generated metadata and isolated synthetic-provider checks cover x86_64/aarch64. Real-distribution install/start-up QA is still missing. - **Done (2026-11-04):** a first frame the app is slow to build no longer costs the window its graphics adapter (#5160). The first-frame watchdog gave the frame 20 s from the app's start and then started again without the adapter, so a slow machine (antivirus reading every file, a large font library) ended with no adapter left and no window. A frame counts once its UI pass ends, before it is painted, so the 20 s now run from there; a frame still being built is waited for, with a note in the log (`a_first_frame_that_never_reaches_the_screen_hangs_its_adapter`; checked on Linux with the first frame held 35 s: the window opened with no restart). Estimate unchanged. - **Done (2026-11-04):** a large font library no longer keeps the window from opening (#5483). The menu bar's Type › Font, drawn in the first frame, waited for the scan of every installed font; when that took longer than the 20 s first-frame watchdog (thousands of fonts on a slow disk, or with each file checked by antivirus) the app took the graphics adapter for hung and started again without it until none was left. The menu now lists the fonts already loaded until the scan ends, then all of them (`the_menu_family_list_now_does_not_wait_for_the_scan`; checked on Linux with 3,923 extra font files, each open delayed 8 ms: the window opened in 1.5 s, where it never did before). Estimate unchanged. - **Done (2026-10-29):** the Linux Flatpak on GNOME no longer reconnects to the compositor and logs a warning every 250 ms when arboard has neither data-control nor X11 (267k warnings in 18 h filled the 16 MB log in 3 h): a clipboard that can't be opened is retried with a wait growing to a minute and logged once. Copy and Paste of text with other apps work there through the core Wayland protocol. - **Unconfirmed (2026-11-13):** pictures and SVG on the clipboard of the Flatpak on GNOME. Copy there offers the PNG as `image/png`, the SVG as `image/svg+xml` (with Include SVG Code on) and the text, all from one Copy; Paste takes SVG, then text, then the PNG (blank text, or text that only names a picture, gives way to the PNG), and the Paste menu item is enabled by the types offered. A read takes 64 MiB at most (`clipboard::wayland` tests; not yet run in the Flatpak on a GNOME session). - **Missing:** the app not starting or staying in the background on some Windows 11 machines (#858, #964 fixed - 2026-10-10, #620, #818), slow pointer on a Linux AppImage (#575), macOS paste from other apps (#954), a + 2026-10-10, #620, #818), macOS paste from other apps (#954), a web-free crash/hang reporter, a field record. - **Evidence:** open issues; the never-crash lints and `guard` stop panics, not driver, windowing or packaging failures. @@ -341,7 +343,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G8 Hardening at scale -- **Implementation awaiting runtime proof (#4569):** bind file-font references to owned document blobs, compare candidate face bytes, and reclaim dead live-face slots. Unused blobs do not consume admission; native/PDF/paste report refused resources. Synthetic text, renderer and native/clipboard regressions added; no gap closed before compilation and runtime checks. +- **Done (#4569):** bind file-font references to owned document blobs, compare candidate face bytes, and reclaim dead live-face slots. Unused blobs do not consume admission; native/PDF/paste report refused resources. Synthetic text, renderer and native/clipboard regressions added and passing in #4569's CI gate; no gap closed. - **Done:** PngSuite fetching verifies 175 original PNGs and redistribution notices against a pinned SHA-256/size manifest before publishing; file and total-size budgets, cache verification and no archive extraction (#1729). The real-world corpus and manual QA gaps below remain. @@ -392,15 +394,14 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi up with the file's size, and blends inside a symbol's art don't count toward a blend whose keys show it. - **Missing:** a corpus of real-world SVG/PDF/EPS files; more Affinity versions and platforms (51 pinned files now, including 28 original Affinity 3.2.3 feature probes; large interacting documents and complex typography - missing); Windows, Linux and browser QA by hand; packaging polish (Homebrew cask #588, Flathub #554, update - checks #615). + missing); Windows, Linux and browser QA by hand; packaging polish (Homebrew cask #588, Flathub #554). - **Impact:** unknown failures on users' files. - **Estimate:** 30–50 h (the corpus and QA part blocks beta). ## 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. @@ -415,7 +416,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done (#1968):** native saves retain transparency grid visibility without adding an edit or undo step; older files default to hidden. Broader G11 scope and estimates unchanged. - **Done:** Asset Export / raster Art Optimized edges supersample so shapes that meet edge to edge leave no ghost seam (#983, #1037; `assets.export` abutting-rects regression; Asset Export panel thumbs use the same supersample). -- **Done (2026-10-14):** Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). A filled Pencil path keeps a stroke of None (#1804, part of #1679). In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). Select › Same matches type on its characters' fill and stroke (#1746, #1737). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). +- **Done (2026-10-14):** Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor followed in #7769). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). A filled Pencil path keeps a stroke of None (#1804, part of #1679). In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). Select › Same matches type on its characters' fill and stroke (#1746, #1737). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). - **Done:** Divide splits filled paths along open cutting lines and curves (#1307), preserving the frontmost filled appearance, implicit filled closure, holes, unrelated objects and one Undo/Redo; the existing bounded-map fallback remains. @@ -435,7 +436,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi selected with Direct Selection (#1839, #1824); Snap to Grid wins over Snap to Pixel (#1840, #1816 unconfirmed); Redo during a drag keeps the drag (#1856, #1719); a template layer dims its images by Dim Images instead of fading the whole layer (#1864, #1683); a failed save or export is reported in a dialog that names the file and stays until - closed, the document left modified (#1865, #1685). Ordinary File > Save now offers Save As for terminal permission/read-only refusals (#6146), unless another picker is open; recovery errors retain the dialog. Regression execution pending; G11 estimate unchanged. + closed, the document left modified (#1865, #1685). Ordinary File > Save now offers Save As for terminal permission/read-only refusals (#6146), unless another picker is open; recovery errors retain the dialog. Regressions pass in #6671's CI gate; G11 estimate unchanged. - **Done:** the Shape Builder offers the empty areas closed shapes enclose as regions, such as the middle of four circles that touch, and merges them with the regions around them (#1691). - **Done (#2523):** Shape Builder Gap Detection shares Live Paint's spatially indexed gap finder, @@ -502,7 +503,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** a paragraph's Auto Leading also sets the Leading the Character panel shows for Auto type, the leading the Alt+↑/↓ nudge steps from and the lines Fill with Placeholder Text counts; estimate unchanged. - **Missing:** CJK vertical - composition (ruby, custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern + composition (custom mojikumi sets and the Mojikumi Settings dialog), Middle Eastern - **Done:** Ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above or below (right of the column in vertical type), aligned, sized, overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present), EPS, EMF/WMF and legacy `.ai` (outlines where ruby is @@ -541,9 +542,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi own pixels until a document takes them in; estimate unchanged. - **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation; Language packs for languages other than English, read from the Craft apps' shared font store, with `proof.packs`, `proof.installPack` and `proof.removePack` (a Preferences page to install them and the missing-pack bar remain). Estimate unchanged. - **Missing:** CJK vertical - composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern + composition (custom mojikumi sets and the Mojikumi Settings dialog), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, installed fonts not yet loaded included, and `type.retype` takes near matches within a tolerance and words outlined as one compound path, in installed fonts not yet loaded too; glyphs fused into one contour, near matches in the panel's list and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, installed fonts not yet loaded included, and `type.retype` takes near matches within a tolerance and words outlined as one compound path, in installed fonts not yet loaded too; glyphs fused into one contour, near matches in the panel's list and text in images remain); optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). @@ -609,8 +610,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Audited (2026-10-30, #394):** every Preferences dialog option but four is read by shipped code, by its field or its key; Highlight Alternate Glyphs (the canvas's render options), Real-time Drawing and Editing (tool previews wait for the commit), Show Tool Tips, Anti-aliased Artwork, Use Precise Cursors and Devices › - Enable Touch Workspace and Touch Gestures included. One of the four, Open Documents As Tabs, acts now (below); - the other three are listed under Missing. + Enable Touch Workspace and Touch Gestures included. Two of the four, Open Documents As Tabs and Hyphenation › Default Language, act now (below); + the other two are listed under Missing. - **Done:** User Interface › Open Documents As Tabs: with the box cleared, each document opened or created afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. @@ -714,9 +715,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the snapping enhancements (29.8.1): forced snapping to the grid, showing guides while snapping, and limiting snapping to the active artboard or to isolated objects; floating-panel parity is unverified (the Control bar's Snapping quick access and View › Snapping submenu are done, see [ui-parity.md](ui-parity.md)). The Smart Guides snapping tolerance and 30.0's Snap to Tangent and Snap to Perpendicular are done. Not yet checked: snapping to the endpoints, midpoints and centers of - rotated objects, and the reworked Snap to Grid and Snap to Pixel feedback. Also missing: artboard colors in exports and print, and + rotated objects, and the reworked Snap to Grid and Snap to Pixel feedback. Artboard colors in exports and print are done (#4991). Also missing: managing artboards from the canvas other than locking and unlocking them from the Artboard tool's right-click - menu (30.0); the Blend panel with ease in/out and separate colour acceleration (30.7). The Dimension tool (28.x) + menu (30.0). The Blend panel's easing (30.7) is partial, see above. The Dimension tool (28.x) is done ([dimensions.md](dimensions.md)). - **Evidence:** Adobe's 30.0 and 30.7 release announcements, see [target-app-parity.md](target-app-parity.md#how-this-was-measured-2026-10-10); snapping: @@ -782,8 +783,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (fifteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Decorative (Leaf Vine, Blossom Chain, Pennant Garland and Lantern String pattern brushes), Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (twenty original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one + bristle brush for each tip shape), Paint, Pattern Borders, Decorative (Leaf Vine, Blossom Chain, Pennant Garland and Lantern String pattern brushes), Ornamental, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching), Arrows (Solid, Open, Double, Chevron and Dashed Arrow), Image Brush, Artistic Brushes and Vector Packs; User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -852,6 +853,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 @@ -1048,6 +1051,7 @@ 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 | 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. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 0c3a73b8cc..cc7c4c656c 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -13,7 +13,7 @@ documentation (GPU Performance, touch workspace, pen pressure pages); ours from the GPU only to composite, so any GPU that can show a window works, at the cost of GPU-accelerated preview on huge documents. VectorCraft reads pen pressure on Windows, on the web, on macOS, and on Linux under X11 and XWayland, and it reads the pen's eraser end on Windows, on macOS, on Linux under X11 and XWayland, and on the web when it presses. -It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and XWayland. +It reads the pen's tilt and barrel rotation on Windows with Windows Ink (#372), on macOS and on Linux under X11 and XWayland. | Feature | Illustrator | VectorCraft macOS | Windows | Linux | Web | Status / hours | |---|---|---|---|---|---|---| @@ -22,14 +22,14 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | | Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | -| 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, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#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 workspace and touch-screen rotation missing, 3–5 h | -| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | +| 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 | 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 | no (one OS window) | no | no | — | missing: 6–10 h (with multiple windows, gap G7) | +| 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 | -| 3D GPU rendering (Materials, ray tracing) | yes | — | — | — | — | blocked on 3D (gap G3) | +| 3D GPU rendering (Materials, ray tracing) | yes | — | — | — | — | missing: 3D and Materials draw on the CPU, shaded or wireframe, with no ray tracing (#1453; gap G3) | ## Revision history diff --git a/docs/mcp.md b/docs/mcp.md index d0521ef3a2..1abd54e70a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -642,7 +642,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 +822,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 +986,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 @@ -2231,9 +2234,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 +2524,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 +2723,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 +2749,11 @@ 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 does `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 +2938,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 +2960,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 ""`, 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 +2992,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: `. 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,8 +3027,9 @@ 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 @@ -3081,7 +3099,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 +3116,92 @@ 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 `-.ai`, and an EPS range goes to `useArtboards`, which writes + `_.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.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 @@ -4406,8 +4512,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 +4522,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 @@ -5280,7 +5387,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 @@ -8566,9 +8676,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 +8767,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 @@ -10535,7 +10650,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 +10795,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 +11113,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 +11218,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 @@ -12490,7 +12611,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}}} @@ -15725,10 +15848,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 +16179,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 +16192,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 +16953,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,8 +16966,9 @@ 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 › +- `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 › Smooth Bridge…). 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 @@ -16851,12 +16977,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 @@ -16867,8 +17000,9 @@ Commands: 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. + (`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with 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), Keep Originals + and Preview. - `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 +17021,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 @@ -17455,6 +17589,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 @@ -17591,7 +17750,7 @@ with strokes and vector effects included and raster effects left out (see its ro 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 @@ -17796,7 +17955,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. @@ -17985,8 +18144,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..cc84d2ef59 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -77,6 +77,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 ff7e13fae7..57b8cd1108 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. @@ -34,7 +34,9 @@ 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. -**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. @@ -158,7 +160,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | 2026-10-12 | minor | Desktop PDF spooler shared through craft-print; exact physical sizes, composed copies and Windows 7 fallback retained. Scores and remaining gaps unchanged. | | Draw and edit paths precisely: Pen, Curvature, Direct Selection on anchors and handles, smart guides and snapping, Pathfinder | yes | `crates/tools/src/pen.rs`, `direct.rs`, `guides.rs` and their tests; 10 exact Pathfinder booleans; [ui-parity.md](ui-parity.md). Shape Builder regions on art of thousands of segments fixed (#937's reproduced case; unconfirmed on the reporter's file), Pathfinder covers the same results | 0 | | Paint and style: fills and strokes, global and spot swatches, gradients, Appearance, transparency, graphic styles | yes | M3 done (92 tasks); area scores 92–97% in [target-app-parity.md](target-app-parity.md#feature-areas) | 0 | -| Set type: point and area type, Character and Paragraph styles, threading, outlines | yes | type core 80%; styles, threading, Create Outlines and font matching tested ([type-parity.md](type-parity.md)); justification options missing (not blocking) | 0 | +| Set type: point and area type, Character and Paragraph styles, threading, outlines | yes | type core 80%; styles, threading, Create Outlines and font matching tested ([type-parity.md](type-parity.md)); justification options set per paragraph with Justification… (#2771) | 0 | | Organise layers and artboards and export assets (Export for Screens, SVG, PNG, PDF per artboard) | yes | Layers panel rework, Artboards panel and tool, Export for Screens and Asset Export done; Art Optimized supersample closes ghost borders (#983 / #1037) | 0 | | Print production: CMYK and spot colour, bleed and marks, PDF/X out, separations preview | yes | PDF/X-1a/3/4, presets, marks and bleed, ICC output intent, Separations Preview, Print with PostScript output | 0 | | Exchange files with Illustrator users: open their `.ai`/EPS/PDF, hand back a file they can open | partial (doesn't block alpha) | `.ai`, EPS and PDF open as editable art, but real files can get the wrong layer structure (#951); Save As `.ai` is PDF-compatible with 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 ([file-format-parity.md](file-format-parity.md)), other objects' effects other than geometry effects left out, and live objects written as their art; #868), or legacy version 7, which keeps layers, groups and type as text, one artboard per file, and waits for users' testing. EPS legacy mesh corners, vector opacity masks and raster print-page comparison now preserve editable art under synthetic regressions. This is the beta main-format gap ([gaps.md](gaps.md) G9) | 10–20 (for beta) | @@ -181,7 +183,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule - **Then:** advanced type (G4) and the Illustrator 2026 additions (G13), then 3D (G3), each with a plan in `plan/` before coding. -- **Alongside:** close the 28 stubbed menu items; run `vectorcraft-cli perf` on an idle machine and fix any +- **Alongside:** close the one stubbed menu item (Effect › 3D and Materials › Materials…); run `vectorcraft-cli perf` on an idle machine and fix any budget missed (G15). - **Beta:** G1, G9, G10, G11, G12, the corpus part of G8, type core, macOS pen pressure and the perf budgets (~170–270 h one agent, ~50–80 h with 4–6 agents). @@ -192,21 +194,21 @@ 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) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); 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 | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets, a ring of overlapping faces broken at one of its own faces (#7023); SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/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 | +| 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) | 🟡 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 , 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 | @@ -262,6 +264,7 @@ 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 | 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 746dc5113b..e9fc82f771 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. > @@ -73,11 +73,13 @@ 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. + 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 +288,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 +348,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, Dimension tool; 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 | | 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 +395,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 +406,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 +424,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 +440,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 +476,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 +489,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 +520,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) | @@ -616,9 +605,9 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Area | Weight | Done | Missing (main items) | One agent (h) | |---|---:|---:|---|---:| | Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | -| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding (Curvature point display improved, #1236 in part) | 8–13 | +| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; the freehand Tool Options' Keep selected (#2246), Alt to the Smooth tool (#2685), Blob Brush Merge Only with Selection (#2367), Touch Type (#2469) and Live Corners' Relative rounding (#3091) are done; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances (Curvature point display improved, #1236 in part) | 8–13 | | Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done; no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, transform nuances (the rotated persistent bounding box and Global Edit of similar groups, #4983, are done) | 4–6 | | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill 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); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | @@ -640,8 +629,8 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | -| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | -| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | +| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu, Consolidate All Windows (#5216) and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, floating panels outside the app window, context menus in the panels that have none, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | +| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu, Consolidate All Windows (#5216) and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, floating panels outside the app window, context menus in the panels that have none, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | @@ -692,12 +681,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 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`. @@ -716,7 +705,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 +716,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 +746,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 +823,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 +832,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 +1075,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 +1117,12 @@ 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.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 +1190,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`. @@ -1383,7 +1375,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`. @@ -1474,7 +1466,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - While Tab or Shift+Tab hides the panels, the Window menu checks no panel, and choosing a panel there, or pressing its function key, shows the dock with that panel in its earlier place instead of closing it; the toolbar and the Control bar stay as they are. In Presentation Mode no panel is checked, and `window.panel` fails and changes nothing. A tool double-click that opens the Gradient or Magic Wand panel and a Character field shortcut also show the hidden dock (`window_panel_from_tab_hidden_dock_reveals_named_front_tab`, `window_panel_from_shift_tab_hidden_floating_window_reveals_it`, `function_key_from_tab_hidden_dock_reveals_named_group`, `presentation_panel_command_reports_unavailable_without_mutating_layout`). - The function key shortcuts for Brushes, Color, Layers, Info, Gradient, Stroke, Attributes, Graphic Styles, Appearance, Align, Transform, Pathfinder, Transparency, and Symbols activate a background tab on the first press, hide its expanded dock or floating group when that tab is in front, and restore the group with all its tabs together on the next press; in an icon column they open and close the flyout while keeping the icons. A reassigned chord keeps that behavior, and Window > a hidden sibling restores the group. - On Windows and Linux, F2, F3 and F4 run Cut, Copy and Paste alongside Ctrl+X, Ctrl+C and Ctrl+V, and in the web build they do so everywhere except macOS. The Edit menu keeps the Ctrl shortcuts, and Keyboard Shortcuts lists both keys of each row. On macOS only Cmd+X, Cmd+C and Cmd+V are the defaults. F2, F3 and F4 do not run these commands in a focused text field or while the Type tool edits text. A saved shortcut set that assigns one of these keys to another command keeps that assignment. Public reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). - - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). + - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story (#5542). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - With text selected in a panel's label, such as a Document Info value, Cmd/Ctrl+C and Cmd/Ctrl+X copy that text and do not copy or cut the art, and so do F3 and F2 where they are Copy and Cut, any other keys assigned to Copy or Cut, and the menu bar's Copy and Cut on macOS. When the selected label is not drawn (the panels are hidden), Copy and Cut act on the art instead (#8432; VectorCraft's own behavior; `selectall::copy_and_cut_copy_the_text_selected_in_a_panel_label`, `selectall::copy_sent_on_from_another_window_copies_the_text_only_when_it_is_this_windows`, `selectall::panel_text_copied_before_the_art_formats_are_written_stays_on_the_clipboard`, `shortcuts::tests::a_window_notes_only_its_labels_copies_until_the_next_main_window_pass`, `shortcuts::tests::a_window_notes_a_copy_of_text_dragged_across_its_label`). Not yet: the in-window Edit menu's Copy and Cut (the click on the menu clears the label's selection first), and, while the selected text is in a floating panel's own window, the menu bar's Copy and Cut, and F3 and F2 (they do not copy the text). - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, locked and hidden frames included, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames`, `textedit::remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames`). @@ -1531,6 +1523,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 +1587,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. @@ -1984,7 +1977,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Paint-only Arabic harakat (marks whose character styles differ only in fill, stroke and related paint) stay inside one shaping cluster so letters keep their joining forms; when a second character-level shaping pass matches the monotone glyphs, a glyph may take a later in-cluster character's run only when GDEF classifies it as a mark (class 3) and that character is a harakat; otherwise it keeps the shaping cluster's first character. Insert Kashidas tatweels take the base letter's paint rather than a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures can leave a mark painted as its letter (`crates/text/src/tests/harakat.rs`). Character panel › Adjust Horizontal and Adjust Vertical Diacritic Position (with the Middle Eastern options; `text.setFormat` or `text.setRangeStyle {diacriticHorizontal, diacriticVertical}`, VectorCraft's own thousandths of an em from -1000 to 1000, 0 by default) move the selected characters' mark glyphs (GDEF class 3) right or left and up or down while the letters stay in place ([the reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549)); an Arabic harakat or Hebrew point styled apart takes its own values, character styles carry both (Character Style Options › Advanced Character Formats edits them), the canvas and PDF draw the moved marks and SVG writes such type as outlines (`tests::harakat::diacritic_positions_move_marks_and_keep_letters`). The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. - The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and Convert to Text are not built yet. + The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog and list levels (#5037) and Convert to Text (#4093) are built too. The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. More Options in the Bullets and Numbered List presets (`ui.bulletsAndNumbering`) opens the Bullets and Numbering dialog ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): a Bullets tab and a Numbers tab with the presets, and the Position group's Alignment, Left Indent and First Line Indent, shown on the type while the dialog is open; OK applies them with `text.setFormat` (Alignment is its `listAlign`) as one undo step, and Cancel puts the type back. Alignment Left starts the marker at the first line's start, and Right ends it where the text starts. The cited page does not say where the marker sits for each choice, so these meanings are VectorCraft's own rule. Paragraph styles and the native file keep the alignment. Tab and Shift+Tab with the caret at the start of a list paragraph (`text.setFormat {listLevel}`), and the Bullets and Numbering dialog's Level field (OK sends it as `listLevel`), move the paragraph down and up the list's nine levels ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html)): each level past the first sets the paragraph 18 pt further in, each level counts its own numbers from 1, and a paragraph back at a shallower level goes on with that level's count, through threaded frames too. Elsewhere Tab inserts a tab as before; one Undo takes a level change back, and paragraph styles and the native file keep the level. Convert to Text writes each level's numbers and keeps a deeper paragraph's indent. @@ -2245,6 +2238,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 (, 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 (). 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` (), 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 (, ). `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 (). 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). @@ -2643,7 +2637,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). - EPS import: `token` on a string, `search` and `anchorsearch` read their strings in place instead of copying the rest of the string on each call, with the same results, errors and operation count as before. Walking a 512 KiB string by what each call leaves takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search`, and a 64 KiB string 2.2 ms instead of 10 ms with `token`; on a 4 KiB string the difference is under 0.1 ms (release build on Linux under load from other builds, median of 7 alternating runs, `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`). -- **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). +- **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; the reporter confirmed it on 0.11.0). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). - **Rendering, later 2026-10-14 merges:** copies, symbol instances and repeats that share an appearance keep their stroke outlines between frames (#1667). Wide drop shadows and glows at high zoom render within the raster budget (#1706); stacked Transform effects are bounded (#1705); 3D effects keep the area a nonzero compound path fills (#1724); pattern tiles redraw when a symbol, pattern or image their art shows changes (#1723); a template layer dims its images by its Dim Images percentage instead of fading the whole layer (#1683) (all #1864). @@ -2896,7 +2890,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) @@ -3304,13 +3298,13 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente ## Spell check engine (2026-11-08) -Edit › Spelling has the commands its Check Spelling dialog will use, as the public documentation describes checking the document's text, suggesting replacements and changing a word ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). `text.spelling.check` lists the words the dictionaries don't know in every visible, unlocked type object, or in the ones given by `ids`, in paint order, each run checked in its Character panel Language (English when it has none; nothing in a language without a dictionary). Each word comes with its object and byte range, which `text.editRange` changes as one undo step. `text.spelling.suggest` gives one word's suggestions. Both come from craft-proof in [storytold/craft-libs](https://github.com/storytold/craft-libs), which checks each paragraph on its own. English words come from the first dictionary craft-proof finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof (#4936; `tests/spelling.rs`). The Check Spelling dialog, Auto Spell Check and Edit Custom Dictionary remain, so the Edit › Spelling menu items are still placeholders. +Edit › Spelling has the commands its Check Spelling dialog uses, as the public documentation describes checking the document's text, suggesting replacements and changing a word ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). `text.spelling.check` lists the words the dictionaries don't know in every visible, unlocked type object, or in the ones given by `ids`, in paint order, each run checked in its Character panel Language (English when it has none; nothing in a language without a dictionary). Each word comes with its object and byte range, which `text.editRange` changes as one undo step. `text.spelling.suggest` gives one word's suggestions. Both come from craft-proof in [storytold/craft-libs](https://github.com/storytold/craft-libs), which checks each paragraph on its own. English words come from the first dictionary craft-proof finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof (#4936; `tests/spelling.rs`). The Check Spelling dialog, Auto Spell Check and Edit Custom Dictionary followed (below; #6341, #6425, #7744). -The custom dictionary and Ignore All followed (2026-11-09), as the same page describes them: Add puts a word in the custom dictionary, which Edit Custom Dictionary adds to, deletes from and changes, and Ignore All skips a word in the current document (#4936). `text.spelling.addWord`, `removeWord` and `changeWord` keep the dictionary in craft-proof, which every language's check reads, and the desktop app saves it to `Custom Dictionary.txt` beside its preferences (none in runs without preferences); `text.spelling.dictionary` lists it. `text.spelling.ignoreAll` keeps a word for the active document while it is open, not saved and not undoable (`tests/spelling.rs`). The dialogs remain. +The custom dictionary and Ignore All followed (2026-11-09), as the same page describes them: Add puts a word in the custom dictionary, which Edit Custom Dictionary adds to, deletes from and changes, and Ignore All skips a word in the current document (#4936). `text.spelling.addWord`, `removeWord` and `changeWord` keep the dictionary in craft-proof, which every language's check reads, and the desktop app saves it to `Custom Dictionary.txt` beside its preferences (none in runs without preferences); `text.spelling.dictionary` lists it. `text.spelling.ignoreAll` keeps a word for the active document while it is open, not saved and not undoable (`tests/spelling.rs`). The dialogs followed (below). -Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › Auto Spell Check underline potential spelling errors with a red line as you type, and says it isn't available for text with effects applied (#4936). `edit.autoSpellCheck` turns it on and off (off at first, saved with the view settings); the canvas draws a red wavy line under each word `text.spelling.check` would list in the visible type, leaves out type with an effect shown on it or on its fills and strokes, and checks a type object again when it is edited, when the custom dictionary changes and when Ignore All adds a word (`ui-egui/src/canvas/tests.rs`, `auto_spell_check_*`; `tests/spelling.rs`). The dialogs remain. +Auto Spell Check followed (2026-11-09): the same page has Edit › Spelling › Auto Spell Check underline potential spelling errors with a red line as you type, and says it isn't available for text with effects applied (#4936). `edit.autoSpellCheck` turns it on and off (off at first, saved with the view settings); the canvas draws a red wavy line under each word `text.spelling.check` would list in the visible type, leaves out type with an effect shown on it or on its fills and strokes, and checks a type object again when it is edited, when the custom dictionary changes and when Ignore All adds a word (`ui-egui/src/canvas/tests.rs`, `auto_spell_check_*`; `tests/spelling.rs`). The dialogs followed (below). -The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs remain. +The right-click followed (2026-11-10), as the same page's "Correct spelling errors during Auto Spell Check" describes it: right-click a word with a red underline, then choose a suggested word, Ignore All to skip it in the current document, or Add to Dictionary (#4936). The canvas context menu lists the words `text.spelling.suggest` gives for it in its run's language, each replacing the word with `text.editRange` as one undo step, or No Suggestions; then Ignore All (`text.spelling.ignoreAll`) and Add to Dictionary (`text.spelling.addWord`). It lists nothing for a word that is right, with Auto Spell Check off, or once the word under the right-click has changed (`ui-egui/src/tests/contextmenu.rs`). The dialogs followed (below). The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, and so does Spelling, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). Check Spelling… followed in the same submenu (2026-11-15), after Auto Spell Check as in Edit › Spelling, as the page also describes opening the Check Spelling dialog from Spelling in the menu of right-clicked text. It runs `ui.checkSpelling` on the selection, which the right-click made the type under the pointer, and a right-click on an underlined word has it too (`right_click_on_type_opens_check_spelling`, `right_click_on_an_underlined_word_also_offers_check_spelling`). @@ -3320,15 +3314,15 @@ Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (` ## Retype, phase 1 (2026-11-18) -The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([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)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape; near matching with a tolerance (below) reads it as the glyph. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Installed fonts not yet loaded and images remain (phase 2). +The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([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)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape; near matching with a tolerance (below) reads it as the glyph. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Images remain (phase 2). Installed fonts not yet loaded, and loaded faces past the first 96, are compared too (#8823; see Retype installed fonts). ## Retype near matches (2026-11-18) -The public page orders Retype's matching fonts by how close each is to the text's appearance ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)), so outlines need not be exactly a font's glyphs. `type.retype` takes a `tolerance` (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, its contours paired with the glyph's by length, and it becomes the glyph it is closest to when the leftover distance, relative to the shape's size, is at most the tolerance and the glyph's outline and the shape's each lie within three times the tolerance (relative to the shape's size, and at least 0.5%) of the other. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is a near match. Each line in the result has a `score` from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours and matched in runs of up to three groups, and becomes type only when every glyph does; exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The tolerance, the score and the splitting are VectorCraft's own. Tested with outlines flattened into lines, restarted, reversed and simplified, a curve split in two, contours in another order, turned lines of round glyphs, a word made into one compound path, and a compound with a part that is no glyph (`crates/engine/src/cmd/retype_tests.rs`, `crates/text/src/retype.rs`). The Retype panel's list (below) still takes exact matches of whole shapes only. Glyphs fused into one contour, installed fonts not yet loaded and images remain. +The public page orders Retype's matching fonts by how close each is to the text's appearance ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)), so outlines need not be exactly a font's glyphs. `type.retype` takes a `tolerance` (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, its contours paired with the glyph's by length, and it becomes the glyph it is closest to when the leftover distance, relative to the shape's size, is at most the tolerance and the glyph's outline and the shape's each lie within three times the tolerance (relative to the shape's size, and at least 0.5%) of the other. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is a near match. Each line in the result has a `score` from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours and matched in runs of up to three groups, and becomes type only when every glyph does; exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The tolerance, the score and the splitting are VectorCraft's own. Tested with outlines flattened into lines, restarted, reversed and simplified, a curve split in two, contours in another order, turned lines of round glyphs, a word made into one compound path, and a compound with a part that is no glyph (`crates/engine/src/cmd/retype_tests.rs`, `crates/text/src/retype.rs`). The Retype panel's list (below) still takes exact matches of whole shapes only. Glyphs fused into one contour and images remain; installed fonts not yet loaded are compared too (#8823, see Retype installed fonts). ## Retype panel (2026-11-18) -The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches and images remain; installed fonts not yet loaded are compared too (see Retype installed fonts). +The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. The Properties panel's Quick Actions show the panel with type selected (#8778). Opening the panel from the Type menu and the context menu, filtering the list by font source and favorites, near matches and images remain; installed fonts not yet loaded are compared too (see Retype installed fonts). ## Retype tracking (2026-11-19) @@ -3390,7 +3384,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s `bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths`, `the_live_paint_bucket_shows_a_bucket_or_a_brush`. Behavior source: [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). - The cursor swatch preview is not built. Scores and estimates unchanged. + Cursor Swatch Preview shows the active paint above the pointer between the swatches before and after it (#7265). Scores and estimates unchanged. - **Live Paint Selection cursors:** the pointer changes over a face, over an edge and outside the Live Paint groups ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). The cursor is the arrow with a filled square where a click selects a face, with a short line @@ -3418,6 +3412,7 @@ 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 | 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. | diff --git a/docs/three-d.md b/docs/three-d.md index a8f220bc59..d5bb4665a9 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -709,11 +709,11 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), graphics on Inflate, shadows of lights after the first, and +- **Materials** (base and Adobe Substance), shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow ([Shadows](#shadows)). Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, and - Revolve's side only ([Graphics](#graphics)). + Revolve's side and Inflate's puffed front and back only ([Graphics](#graphics)). - The bevel shapes and their names are our own. Custom bevels come from VectorCraft's own bevels file ([Custom bevels](#custom-bevels)) and are cut into straight lines. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn @@ -766,7 +766,7 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in Separations Preview and PDF output. Their Rotation tab has the track cube ([Track cube](#track-cube)). Extrude & Bevel (Classic) and Revolve (Classic) take Map Art - ([Map Art](#map-art)). Turntable and 3D export are separate, unbuilt items. + ([Map Art](#map-art)). Turntable is a separate, unbuilt item. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). diff --git a/docs/type-parity.md b/docs/type-parity.md index 1587d7f8f1..9d3d069cc8 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -57,10 +57,10 @@ 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, the context menu and the Properties panel's Quick Actions, 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) | +| 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) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | 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 still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | @@ -70,7 +70,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Middle Eastern & South Asian composers and Standard composers (Paragraph panel menu, paragraph styles, `text.setFormat {composer}`) | done / partial | #4935: per paragraph, four choices. Middle Eastern & South Asian Single-line and Every-line are how all type was already set (complex-script shaping on) and stay the default, so existing documents do not change. Standard Single-line and Every-line break lines the same way and set Indic, Arabic and Hebrew type glyph by glyph as the font maps its characters (no conjuncts, reordering, mark placement or joining), for legacy fonts that keep a script on Latin character codes. Indic, Arabic and the other joining scripts and Hebrew are the scripts left unshaped (their letters do not join, so Insert Kashidas adds no tatweel); Latin, Greek, Cyrillic, CJK, Thai and the rest keep their kerning and ligatures. The native file and paragraph styles keep the choice (`standardSingleLine` / `standardEveryLine`; an older VectorCraft cannot read a file that uses them). `.ai`, EPS and PDF import and export carry no composer: this app has no recorded format for it, so a Standard paragraph opened from or saved to those files comes back Middle Eastern & South Asian. Evidence: `tests::composers`, `tests::panelcmds::text_set_format_takes_the_four_composers`, `native_v3::all_four_composers_round_trip` | | Middle Eastern: split caret | missing | Character Direction is done; editable bidirectional SVG text remains incomplete. | | CJK: input methods (marked text, candidate window) | done | | -| CJK: kinsoku (Hard, Soft, None), the predefined mojikumi sets (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku, YakumonoZenkaku, with VectorCraft's own spacing for each) and Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, custom mojikumi sets and the Mojikumi Settings dialog missing | +| CJK: kinsoku (Hard, Soft, None), the predefined mojikumi sets (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku, YakumonoZenkaku, with VectorCraft's own spacing for each) and Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets done (Type › Kinsoku Shori Settings…, #7229); custom mojikumi sets and the Mojikumi Settings dialog missing | | CJK: Kinsoku Shori Type (Push In First, Push Out First, Push Out Only) | done | Paragraph panel menu › Kinsoku Shori Type (`text.setFormat {kinsokuType}`), with the East Asian options ([Formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); Push Out Only is the default, and a push-in closes the line's gaps next to CJK characters by at most a tenth of an em each (VectorCraft's own limit). Evidence: `layout::wrapping_tests::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `tests::vertical::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `typecmd::area_tests::kinsoku_shori_type_is_set_per_paragraph_and_saved_only_when_not_push_out_only` | | CJK: Kurikaeshi Moji Shori | done | Paragraph panel menu › Kurikaeshi Moji Shori (`text.setFormat {kurikaeshiMojiShori}`), with the East Asian options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, and the text keeps the mark; SVG export with live type writes the drawn character. The set of marks and the voicing rules are VectorCraft's own. Off by default, saved natively only when on, carried by paragraph styles. Evidence: `tests::repeat_marks_stand_for_the_character_before_them`, `tests::kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start`, `typecmd::area_tests::kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on`, `threads::tests::a_continued_frame_carries_the_character_a_repeat_mark_stands_for`, `panels::paragraph::tests::kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs`, `text_layout::a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws` | | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 18c760b936..84c1ab8010 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,7 +1,7 @@ # 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. > @@ -25,7 +25,9 @@ ## 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. + +**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 +170,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,12 +206,12 @@ 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` | @@ -243,14 +245,14 @@ tools, never checked side by side) isn't captured row by row. | Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | | Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | | Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | -| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | -| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings; simplifying only a Direct Selection part of a path remains missing | +| Simplify (slider, auto, corner angle threshold) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at the Auto-Simplify level (#3750), and with part of a path direct-selected only the selected runs are simplified (#3814) | +| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings; with part of a path direct-selected, only the selected runs are simplified (#3814) | ## Direct Selection, anchors and handles | 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 +271,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 +352,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 +407,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 | | @@ -500,7 +502,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | | Actions panel: ≡ › Button Mode shows each action by name as a button in its Action Options color, without sets or steps; a click on a button plays the action, and choosing Button Mode again shows the list ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.action.buttonMode`, `ui.action.playAt`; `panels/actions.rs` tests. VectorCraft's own rules: every set's actions show in set order, an action without a color is an ordinary button, the mode is kept with the UI preferences, and it cannot be turned on while an action records | | Actions panel: ≡ › Playback Options… plays actions Accelerated, Step by Step or with a pause between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html)) | done | `ui.action.playbackOptions`; `panels/actions.rs` tests. The pause is a whole number of seconds from 1 to 60 (VectorCraft's own range); Batch… plays at full speed | -| Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | +| Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions remains; New Action (#5270) and Action Options set a function key that plays the action | | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | | Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode shows the color | | Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | @@ -523,7 +525,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | 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) | | 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 solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | +| 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 | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | | Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | | Pathfinder Divide: an open cutting line splits a filled path | done | #1307; straight, crossed, bent and curved cutters, holes and frontmost appearance regression-tested; native automation: independent piece movement, one Undo/Redo, saved-document round trip and window capture; existing bounded-map fallback remains | @@ -532,6 +534,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | 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 | | 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`. | @@ -673,6 +676,7 @@ 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 | 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. | @@ -719,6 +723,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 | diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 9738b641bd..2729b40282 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -244,15 +244,21 @@ class TrustedSourcePreparation(unittest.TestCase): self.assertTrue(literal_off("${{ false }}")) self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')")) - def test_no_nightly_schedule_is_registered(self): - for name, event in (("nightly.yml", "workflow_dispatch"), - ("nightly-sign.yml", "workflow_dispatch")): + def test_nightly_triggers_and_schedule_contract(self): + expected_triggers = { + "nightly.yml": [" schedule:", " workflow_dispatch:"], + "nightly-sign.yml": [" workflow_dispatch:"], + } + for name, expected in expected_triggers.items(): source = (ROOT / ".github/workflows" / name).read_text() events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] triggers = [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] with self.subTest(workflow=name): - self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + self.assertEqual(triggers, expected, "workflow triggers must match the reviewed schedule contract") + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + crons = re.findall(r"(?m)^ - cron: '([^']+)'$", producer) + self.assertEqual(crons, ["30 6 * * *"], "scheduled nightly cadence must stay at 06:30 UTC") def test_signer_serialization_contract_is_enforced(self): assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) @@ -387,7 +393,8 @@ class NightlyEnabledCallers(unittest.TestCase): source = (ROOT / ".github/workflows/nightly.yml").read_text() policy = json.loads(INSTALLED_POLICY.read_text()) self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) - self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"], + "scheduled dispatch signs only as github-actions[bot]") def test_an_actor_outside_the_release_managers_is_refused(self): source = (ROOT / ".github/workflows/nightly.yml").read_text() @@ -869,19 +876,24 @@ def dispatch_triggers(source): class NightlyDispatchTransport(unittest.TestCase): - """The scheduled transport stays literally off and can only reach the signer branch.""" + """The scheduled transport keeps its exact context guard and can only reach the signer branch.""" + + EXPECTED_GUARD = "github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_run'" def setUp(self): self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() - def test_every_dispatch_job_is_literal_off(self): + def test_dispatch_job_keeps_exact_context_guard(self): jobs = self.source.split("\njobs:\n", 1)[1] headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) conditions = job_conditions(jobs) - self.assertTrue(headers) - self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") - for _, expression in conditions: - self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + self.assertEqual(headers, [" dispatch:"]) + self.assertEqual(len(conditions), 1, "dispatch job needs its exact context guard") + indicator, expression = conditions[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), self.EXPECTED_GUARD, + "dispatch context guard may only change with review") + self.assertFalse(literal_off(expression), "scheduled dispatch transport must be enabled") def test_only_a_completed_scheduled_producer_is_transported(self): self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source), diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 index 51a8e2ade9..535ad4e222 100644 --- a/packaging/windows/nightly-signing-tests.ps1 +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -73,6 +73,29 @@ try { Clear-SigningFixtures Write-Output 'PASS: supported-configuration-presence-without-signing' + # The unsigned message is captured here, so it does not become an annotation of this job. + $optInFile = Join-Path $root 'opt-in-sentinel.exe' + [IO.File]::WriteAllText($optInFile, 'generated sentinel, not a real executable') + $savedActions = $env:GITHUB_ACTIONS + try { + $env:GITHUB_ACTIONS = 'true' + $env:CRAFT_ALLOW_UNSIGNED = $null + $default = (& $sign $optInFile) -join "`n" + Assert-Policy ($default.Contains('::warning::Windows signing secrets not set')) "unsigned output without the opt-in must warn; got: $default" + $env:CRAFT_ALLOW_UNSIGNED = '1' + $optedIn = (& $sign $optInFile) -join "`n" + Assert-Policy ($optedIn.Contains('::notice::Windows signing secrets not set')) "opted-in unsigned output must be a notice; got: $optedIn" + Assert-Policy (-not $optedIn.Contains('::warning::')) "opted-in unsigned output must not warn; got: $optedIn" + foreach ($value in @('true', '0', 'yes')) { + $env:CRAFT_ALLOW_UNSIGNED = $value + Invoke-Refusal { & $sign $optInFile } 'CRAFT_ALLOW_UNSIGNED must be 1 or unset' + } + } finally { + $env:CRAFT_ALLOW_UNSIGNED = $null + $env:GITHUB_ACTIONS = $savedActions + } + Write-Output 'PASS: opted-in-unsigned-output-is-a-notice' + # Load the policy function without signing. These objects are not crypto evidence. . $sign -CheckOnly foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 11a391dd60..2a768c7338 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,8 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. Nightly callers require signing with -Required and can check the + still produce installers. A caller that builds unsigned on purpose sets CRAFT_ALLOW_UNSIGNED=1, + and the message is then a notice instead of a warning. Nightly callers require signing with -Required and can check the signing configuration with -Required -CheckOnly. Compilation uses the separate -CheckBuildEnvironment mode, which refuses any signing material without importing a key. @@ -38,6 +39,10 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +function Write-Note([string] $Message) { + if ($env:GITHUB_ACTIONS) { Write-Output "::notice::$Message" } else { Write-Output $Message } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -64,6 +69,11 @@ if ($CheckBuildEnvironment) { } return } +$allowUnsigned = switch -CaseSensitive ([string]$env:CRAFT_ALLOW_UNSIGNED) { + '' { $false } + '1' { $true } + default { throw "CRAFT_ALLOW_UNSIGNED must be 1 or unset, got '$env:CRAFT_ALLOW_UNSIGNED'" } +} $haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) @@ -78,7 +88,8 @@ if (-not $Files) { throw 'At least one file is required for signing' } $Files = $Files | ForEach-Object { (Resolve-Path $_).Path } if (-not $haveCert -and -not $haveAzure) { - Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" + $message = "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" + if ($allowUnsigned) { Write-Note $message } else { Write-Warn $message } exit 0 } diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index a284579d16..250fd92b1c 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -129,18 +129,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} diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3b913d68f7..e285fef70b 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -18,9 +18,10 @@ were deleted leaves no rolling entry, so the next run starts cold, and this exit 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. +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 @@ -36,7 +37,12 @@ WARM_JOB = re.compile(r'^gate / cache warm \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of # them fails or is canceled, the legs are skipped and no warm leg is listed. NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') -PRUNE_JOB = 'cache prune' +# 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). @@ -135,9 +141,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]) @@ -185,7 +192,7 @@ 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', [])): diff --git a/sonar-project.properties b/sonar-project.properties index 9523d64b0e..1e6165455f 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -10,6 +10,17 @@ sonar.sources=. sonar.tests=. sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,**/tests_*.rs +# The coverage job writes lcov.info at the root, where sonar.sources=. would index it. +sonar.exclusions=lcov.info + +# Duplication skips test files, the UI command table and the MCP catalog generated from it. +# The shared Sonar workflow reads this property from a single line and adds **/i18n/** to it. +sonar.cpd.exclusions=**/tests/**,**/tests.rs,**/*_tests.rs,**/tests_*.rs,crates/ui-egui/src/menus/ui_commands.rs,crates/mcp/src/ui_catalog.rs + +# CI runs the scripts in packaging/ and scripts/ with Python 3.12 (Ubuntu 24.04), 3.13 +# (setup-python in the nightly jobs) and 3.15 (macOS 15). +sonar.python.version=3.12, 3.13, 3.14, 3.15 + # S4790 (weak hash): MD5 is the key derivation of the PDF standard security handler revisions 2-4 # (ISO 32000-1 §7.6.3.3), which PDF 1.3-1.6 files use. It is needed to read those files and to write # the compatibility the user picks, not chosen for new security: the default is 256-bit AES @@ -18,3 +29,6 @@ sonar.issue.ignore.multicriteria=pdf_md5 sonar.issue.ignore.multicriteria.pdf_md5.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.pdf_md5.resourceKey=crates/pdf/src/encrypt.rs sonar.coverage.exclusions=packaging/** + +# Produced by the shared workflow Python coverage step. +sonar.python.coverage.reportPaths=python-coverage.xml 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..1c9af7db00 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,11 @@ 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 ] [--all] + weak tests in the lines changed since the base: fail on self-compares, reasonless + #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, + early returns, unset env gates... (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,7 +45,7 @@ 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 @@ -74,6 +80,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 +125,13 @@ pub fn root() -> PathBuf { pub fn repo_files(root: &Path) -> Result, 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 +274,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) -> 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,11 +402,13 @@ 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. /// /// 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. @@ -414,9 +425,8 @@ fn cmd_ci_warm() -> Result<(), String> { 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) }), )); } @@ -447,6 +457,13 @@ fn cmd_ci_warm() -> Result<(), String> { 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 /// and, after a failure, the one that failed and those skipped. fn run_steps(steps: &[Step]) -> Result<(), String> { @@ -515,6 +532,7 @@ fn ci_steps() -> Vec { ("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 +606,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 = 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 f4f02f8627..216d23d43d 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 = "186a229c8da8db5916f8a863dfd894f1879af735"; +const REV: &str = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..8609ace2f5 --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,3991 @@ +//! `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; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk +//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. +//! +//! 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 ` 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` and `sleep` in +//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` 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; +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, +} + +impl Rule { + pub const ALL: [Rule; 10] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + ]; + + 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", + } + } + + 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", + } + } + + /// 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) + } + + fn from_id(id: &str) -> Option { + 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`, 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, +} + +impl Hit { + 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 and the variables CI sets. +pub struct Ctx { + pub helpers: HashMap>, + pub ci_env: HashSet, +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let hits: Vec = 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>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); + let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; + let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let (mut counted, mut older) = (vec![], 0usize); + for (path, src) in read_all(root, &present)? { + for hit in lint_file(&path, &src, &ctx) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + counted.push(hit); + } else { + older += 1; + } + } + } + finish(&counted, older, present.len(), &base) +} + +/// The command line: `--all`, `--base `. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + 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 ])")), + } + } + 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.rule.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} `):\n {}", + failing.len(), + listing(&failing).join("\n ") + )) +} + +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec { + let mut out: Vec = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet = 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> = 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 = 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/` or `apps/` 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, 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 { + 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) -> Result { + 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 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>>, String> { + let diff = git( + root, + &[ + "-c", + "core.quotepath=off", + "diff", + "-U0", + "--inter-hunk-context=0", + "--no-color", + "--no-ext-diff", + "--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>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let mut current: Option = 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); + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file) = (true, false); + } else if header && line.starts_with("new file mode") { + new_file = true; + } 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(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 { + 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>) -> bool { + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result, String> { + let mut names: HashSet = 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 + '_ { + 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 { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec { + 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 { + 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 = 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 { + 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 { + 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 { + 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::>()).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec); + +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 { + let mut out: Vec = 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 { + // 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 { + 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)> { + 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((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) -> 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!") + || contains(body, b".unwrap_err()") + || contains(body, b".expect_err(") + || 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 = 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); + +/// 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> { + let mut defs: HashMap> = 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 + Clone) -> HashSet { + 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 = HashSet::new(); + loop { + let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); + let more: Vec = 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 { + 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, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec, + lines: Lines, + tests: Vec, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, +} + +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 } + } + + 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 { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let exec = executed(&m, &tests); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; + let mut hits: Vec = 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 { + 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, + delegates: bool, + checks: bool, + should_panic: bool, +} + +fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { + let m = &file.exec; + let asserts: Vec = 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([only_weak(&v), exit_status_only(&v), no_assertion(&v)].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 { + 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 { + 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() +} + +/// 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 { + 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 = 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 { + 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 { + 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 { + 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 { + 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 = 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>, +} + +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 { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option { + 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 = ;` 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 { + // `None` for a name declared with a value that is not a literal or with different values. + let mut out: HashMap> = 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, + end: usize, + counts: bool, + /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). + source: Option>, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec { + 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 { + 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!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err("); + 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 { + 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 { + 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 { + 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 { + 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 { + 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 = 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 { + 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 + '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 { + 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 = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +fn sleep_hits(file: &File) -> Vec { + let m = &file.m; + // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. + let imported = words(m, b"use", 0, m.len()).into_iter().any(|u| { + let item = norm(&m[u..statement_end(m, u)]); + item.contains("thread::sleep") + || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"sleep", 0, list.len()).is_empty()) + }); + 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); + 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"), + } + }) + .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) + .collect() +} + +fn reads_source_hits(file: &File) -> Vec { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + let mut out = vec![]; + for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + 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(&file.src[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 = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; + if rs { + out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + } + + /// 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 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::>()", + "(0..0).collect::>()", + "(3..1).collect::>()", + "(0..n).collect::>()", + "(0..).take(3).collect::>()", + "[1, 2].iter().filter(|x| keep(x)).collect::>()", + "[1, 2].into_iter().zip(ys).collect::>()", + "[None::].into_iter().collect::>>()", + "[Err::(error())].into_iter().collect::, E>>()", + "[1, 2].into_iter().collect()", + "[1, 2].into_iter().collect::()", + "[1, 2].into_iter().collect::>()", + ] { + 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 = [1, 2].iter().copied().rev().collect();", + "let xs: Vec = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::>();", + "let xs = (-2..1).step_by(2).collect::>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::>().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::>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::>();", + "let xs = [None::].into_iter().collect::>>();", + "let xs = [Err::(error())].into_iter().collect::, E>>();", + "let xs: Option> = [1].into_iter().collect();", + "let xs: Result, 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::].into_iter().collect::>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::();", + ] { + 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::();", + ] { + 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::>();"), + ] { + 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 }\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 }}\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", "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::>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::>()", + "&xs.iter().copied().rev().collect::>()", + ] { + 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::>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::>().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::>()", + "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> = xs.iter().copied().collect();", + "let ids: Result, 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::>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option>", "Result, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::>()"); + 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::()"); + 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::(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::()", "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::()", "f::>()", "f :: ()"] { + 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, ci_env: HashSet::new() }; + 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 { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::()", "check_round_trip::>(x)", "value.check::()", "value.check :: >> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::", "value.check::", "round_trip::()", "value.round_trip::()"] { + 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(a: T, b: T) { assert_eq!(a, b); }\nfn twice(a: T) { same::(a, a); }\nfn idle() {}\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, ci_env: HashSet::new() }; + for call in ["same::(a, b)", "twice::>>(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::()", "same::", "value.same::()"] { + 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 = 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 = [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"]); + 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 = 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 = 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::::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::>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::>(), Vec::::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::::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 { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + 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 { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + 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::::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::>(), ["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::>(), [(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, ci_env: HashSet::new() }), [(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, ci_env: HashSet::new() }), []); + } + + #[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::>(), [(Rule::EnvGateUnset, 3, 3, 4)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone"); + } + + #[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}"); + } + 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 { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + 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::>(), [(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 = 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 = 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 = (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::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); + } +}