Merge main into feat/group-rows

This commit is contained in:
dotCooCoo committed 2026-12-01 01:03:49 -08:00
commit 3fcb278b24
282 files changed
+18343 -2613

No files matched your search

+3 -1
View File
@@ -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",
+74
View File
@@ -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('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="140">'
'<rect x="20" y="20" width="160" height="100" rx="12" fill="#2463eb"/>'
'<circle cx="100" cy="70" r="30" fill="#ffcc33"/></svg>')
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"))
@@ -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()
+5 -6
View File
@@ -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]
+2 -28
View File
@@ -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
+2 -2
View File
@@ -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
+3 -2
View File
@@ -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:
+114
View File
@@ -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
+1
View File
@@ -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 }}
+3
View File
@@ -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
Generated
+190 -178
View File
File diff suppressed because it is too large. Load diff
+52 -50
View File
@@ -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" }
+2 -2
View File
@@ -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).
+29 -29
View File
@@ -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
+11
View File
@@ -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",
]
+1 -1
View File
@@ -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 }
+1
View File
@@ -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 }
+53 -11
View File
@@ -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");
}
}
+13 -51
View File
@@ -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)");
}
}
+117 -16
View File
@@ -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<Startup>) {
// 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<String>, 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<String>, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec<String>, 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<eframe::Result, String>, 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 _;
+43 -6
View File
@@ -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.
+82 -203
View File
@@ -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 <abs> -- [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 <abs> -- [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<OsString>,
}
static PROFILE: OnceLock<Profile> = 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<OsString>) -> Result<Launch, String> {
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<PathBuf, String>) -> Result<Launch, String> {
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<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable)
pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
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<OsString> {
child_args_for(current(), files)
@@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec<OsString> {
#[cfg(not(target_os = "macos"))]
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
let mut args: Vec<OsString> = 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<OsString> = 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<OsString> {
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<OsString> {
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"]));
}
}
+113 -53
View File
@@ -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<vectorcraft_ui_egui::state::LegacyWindow>, 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<Vec<std::ffi::OsString>> {
// 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 <dir>
// --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<Vec<std::ffi::OsString>> {
// 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<String> {
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!(
+173 -610
View File
@@ -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<Self, String> {
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<PathBuf, String> {
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<OsString>, key: &str) -> Result<PathBuf, String> {
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<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
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<PathBuf, String> {
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<PathBuf, String> {
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::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
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<OsString>, exe: &Path) -> Result<Vec<PathBuf>, 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::<Result<Vec<_>, _>>()?;
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::<Result<Vec<_>, _>>()?;
// 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::<Result<Vec<_>, _>>()?;
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<Path>, label: &str) -> Result<PathBuf, String> {
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<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
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<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
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<PathBuf> {
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<OsString>, exe: Option<&Path>) -> Vec<PathBuf> {
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<String, OsString>,
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<OsString> {
self.env.get(key).cloned()
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
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());
}
}
+2 -2
View File
@@ -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));
+68 -3
View File
@@ -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<u16, Device>,
last: HashMap<u16, [Option<f32>; 5]>,
/// The pens an event has come from, for the log.
heard: HashSet<u16>,
}
impl Pens {
@@ -197,10 +199,37 @@ impl Pens {
/// same id starts without them.
fn set_devices(&mut self, devices: impl IntoIterator<Item = Device>) {
let devices: HashMap<u16, Device> = 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<Item = (u16, f64)>) -> 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<f64> = 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);
+62 -113
View File
@@ -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
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). 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.
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). 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<AltCodes> = 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<u16>,
/// 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<usize> {
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<u16> = 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<Event>) {
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)]);
+110 -20
View File
@@ -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<OsString>, 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<Option<String>, 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<OsString>, 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<String> {
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<OsString>, 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::<Vec<_>>().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\
+4
View File
@@ -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"]
+8 -6
View File
@@ -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)) {
+27 -10
View File
@@ -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::<Result<Vec<_>, 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<usize> = 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<usize> = 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<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
let per_face = items
@@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, 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<SolidLayout> = 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<usize> = 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<usize>, 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<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None)
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None)
.collect::<Result<Vec<_>, 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<usize>, 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() {
+28 -6
View File
@@ -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}");
+3 -3
View File
@@ -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<Vec<WireFac
}
let (parts, bounds) = solid_parts(shapes, b);
// The solids the art draws, each past the limits of the object's solids together as it is.
for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) {
for f in built_solids(&fx.id, &p, &parts, bounds, object_face_limit()) {
out.extend(f?.iter().flatten().map(face));
}
Ok(out)
+16 -4
View File
@@ -72,10 +72,11 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in
# Cargo.lock (tempfile, ui-egui), so this adds no new crate.
# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a
# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile,
# ui-egui), so this adds no new crate.
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true, features = ["std", "process"] }
rustix = { workspace = true, features = ["std", "process", "fs"] }
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
@@ -116,7 +117,7 @@ zune-core = { workspace = true }
# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs).
craft-jxl = { workspace = true }
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
# tests/group3_reference.rs compares it with.
# tests/it/group3_reference.rs compares it with.
hayro-ccitt = { workspace = true }
craft-stream-codecs = { workspace = true }
vectorcraft-affinity = { workspace = true, features = ["synth"] }
@@ -143,3 +144,14 @@ ruzstd = { workspace = true }
vectorcraft-js = { workspace = true }
# A bundled font's own glyph boxes, for the glyph bounds tests.
skrifa = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"crates/affinity/tests/support/corpus.rs",
"crates/affinity/tests/support/text_fixture.rs",
"crates/apischema/src/conformance.rs",
"crates/plugins/tests/fixtures/desaturate.wasm",
"xtask/affinity-corpus.sha256",
"xtask/src/sha256.rs",
]
+22 -1
View File
@@ -111,6 +111,7 @@ mod textedit;
pub use textedit::effective_kerning;
mod retype;
mod stepandrepeat;
pub mod textstyles;
pub(crate) mod textwrap;
pub(crate) mod threads;
@@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layerpanel::specs());
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(stepandrepeat::specs());
v.extend(effectcmd::specs());
v.extend(bevels::specs());
v.extend(wireframe::specs());
@@ -677,8 +679,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option<Affine> {
}
/// 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<Color> {
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<Color> {
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};
@@ -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<CommandSpec> {
"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<Value> {
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<Value> {
}
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<Value> {
made.push(top);
gone.extend_from_slice(rest);
}
let parents: Vec<NodeId> = 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<Value> {
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<NodeId> {
fn visit(n: &Node, out: &mut Vec<NodeId>) {
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<NodeId>) -> 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<NodeId> {
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
@@ -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<NodeId> {
(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<NodeId> {
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::<NodeId>::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::<Vec<_>>()})).unwrap()["id"].as_u64().unwrap())
}
fn children(s: &Session, id: NodeId) -> Vec<NodeId> {
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);
}
+127 -5
View File
@@ -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<CommandSpec> {
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<Value> {
}
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<AnchorRef>) -> BTreeSet<AnchorRef> {
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<AnchorRef>) -> BTreeSet<AnchorRef> {
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<Value> {
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<NodeId> = sel.objects.iter().copied().filter(|id| sel.anchors.contains_key(id)).collect();
let mut kept: Vec<(NodeId, usize, Option<BTreeSet<AnchorRef>>)> = 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<NodeId> = kept.iter().map(|(id, ..)| *id).collect();
let anchors: BTreeMap<NodeId, BTreeSet<AnchorRef>> = 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 }))
}
@@ -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<NodeId>, BTreeMap<NodeId, BTreeSet<(usize, usize)>>);
/// 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<NodeId> = 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");
}
}
+15 -2
View File
@@ -139,7 +139,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
}
/// 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<NodeId>,
@@ -956,6 +956,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
let mut ids = row_targets(s, p, cmd)?;
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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
),
+11 -4
View File
@@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
}
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<Brush>, renames: &[(String, Option<String>)]) -> 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<Value> {
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 }))
+1 -1
View File
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -563,13 +563,16 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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::<Vec<_>>(), "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::<Vec<_>>(), "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<Value> {
+63 -7
View File
@@ -39,6 +39,15 @@ pub fn specs() -> Vec<CommandSpec> {
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<CommandSpec> {
"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<CommandSpec> {
"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<Value> {
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
}
fn doc_set_saved(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
let n = s.documents().len();
let from = match p.get("from") {
@@ -967,7 +996,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
}
#[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<Vec<NodeId>> {
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<NodeId>, HashMap<NodeId, Vec<usize>>) {
let paths = doc.index_paths(objects.iter().copied());
let mut ids: Vec<NodeId> = 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<Vec<NodeId>> {
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
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<NodeId>) -> Vec<NodeId> {
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// 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<NodeId>, paths: &HashMap<NodeId, Vec<usize>>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// A compound-path member acts as its compound (compounds are one object).
let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
.into_iter()
@@ -1105,7 +1153,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
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<Value> {
});
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() }))
+30
View File
@@ -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<u64> = all.iter().rev().map(|id| id.0).collect();
s.execute("select.set", &json!({"ids": reversed})).unwrap();
type Find = fn(&Session) -> Vec<NodeId>;
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]
+9
View File
@@ -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};
+30 -1
View File
@@ -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<Vec<u8>> {
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<Vec<u8>> {
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
+9 -1
View File
@@ -73,7 +73,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, 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<Value> {
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)?;
}
+16 -1
View File
@@ -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<Value> {
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);
+7 -3
View File
@@ -22,6 +22,8 @@ pub struct LoadOptions {
pub pages: Option<String>,
/// 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<String>,
/// 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<ImportOptions> {
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 },
+19 -4
View File
@@ -602,6 +602,7 @@ pub struct SaveJob {
stamped: Option<i64>,
/// The artboards also saved to files of their own (`separateArtboards`).
boards: Vec<usize>,
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<i
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
}
impl SaveJob {
@@ -1044,7 +1045,8 @@ impl SaveJob {
}
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
/// order: when `stop` returns a value, nothing is written and that value is returned. When a
/// save writes several files and the file access in force refuses one, none is written. Work
/// canceled ([`crate::cancel`]) before the first file is written returns
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
/// others are written too.
@@ -1069,6 +1071,18 @@ impl SaveJob {
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
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<Value> {
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<CommandSpec> {
"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 <name>-<artboard>.<ext> 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 <name>_<artboard>.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 <name>-<artboard>.<ext> 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 <name>_<artboard>.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)
),
+8 -3
View File
@@ -172,14 +172,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
/// Editing Capabilities).
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
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<u8> {
+157 -9
View File
@@ -267,6 +267,8 @@ thread_local! {
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = 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<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many objects [`matches`] looked at on this thread.
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Form {
@@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
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<Highlights> {
out
}
/// [`similar`]'s outlines as of a document revision and the options they were found with.
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
/// [`similar`]'s outlines as of a document revision, with what they were found from.
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
/// [`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<Document>,
key: NodeId,
isolation: Option<NodeId>,
out: Arc<Highlights>,
}
/// 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<Highlights> {
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<Node>], now: &'a [Arc<Node>], 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<Node>]> {
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 {
+71 -15
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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<Item = &'static str> {
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<Value> {
// 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<Value> {
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<Value> {
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 }))
+1 -1
View File
@@ -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};
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+12
View File
@@ -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.
+75 -10
View File
@@ -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<bool> {
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<NodeId, Vec<usize>>) -> Result<bool> {
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<usize>, Arc<Node>)> = 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::<Vec<_>>() }))
}
/// The node at index path `path` of `d`, shared.
fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
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<Document>, st: &crate::DocState, held: &[(Vec<usize>, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
let d = &st.doc;
let unchanged = |(p, n): &(Vec<usize>, Arc<Node>)| 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<Value> {
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);
+41 -4
View File
@@ -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<u64> = const { std::cell::Cell::new(0) };
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -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<NodeId> {
transparency_targets(self, &Value::Null).ok()?.first().copied()
}
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
@@ -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");
}
}
+3 -2
View File
@@ -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<NodeId> {
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)
}
}
+52
View File
@@ -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<NodeId> = (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() {
+6 -6
View File
@@ -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<Value> {
/// 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::<vectorcraft_color::Color>(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::<vectorcraft_color::Color>(v.clone()).is_ok_and(|c| color_is_finite(&c)),
_ => false,
}
}
@@ -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",
+2
View File
@@ -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");
+141
View File
@@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
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<usize> = 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<NodeId>>) -> bool {
struct Seen<'a> {
first: Option<ColorKey>,
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<NodeId>>) {
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<u64> = (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() {
+233
View File
@@ -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<CommandSpec> {
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<Cell> {
(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<usize> {
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<Option<Rect>> {
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<Value> {
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<Node>)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect();
let mut copied: Vec<NodeId> = 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<NodeId> = roots.clone();
out.extend(copied);
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
}
#[cfg(test)]
mod tests;
@@ -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::<Vec<_>>(), [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<u64> = 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<u64> = 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<u64> = 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<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let d = &s.doc().unwrap().doc;
let order: Vec<u64> = 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<u64> = 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<Value>| {
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);
}
+167 -12
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
"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<f64> = -1000.0..=1000.0;
@@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
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<NodeId> {
let wanted: HashSet<NodeId> = 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<usize, usize> = 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<Value> {
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<NodeId> = 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::<Vec<_>>() }))
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::<Vec<_>>() });
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<Value> {
@@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
fn options(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId> = 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<vectorcraft_doc::TextWrap> {
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();
+8 -4
View File
@@ -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))
+53
View File
@@ -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<SelectionRecord>,
/// 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<Option<OutsideLivePaint>>,
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
/// Not saved.
pub moved: Option<Moved>,
}
/// 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<Document>,
ids: Vec<NodeId>,
}
/// 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<Document>,
pub to: std::sync::Weak<Document>,
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<usize> = 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<usize> = 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<usize> = 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<NodeId> {
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
+52 -4
View File
@@ -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<String>,
/// 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<PathBuf>,
/// 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, "<svg/>").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, "<svg/>").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, "<svg/>").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"] {
+17
View File
@@ -10,6 +10,10 @@ pub struct Interaction {
pub doc: Arc<Document>,
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
pub(crate) active_appearance_item: Option<PreviewAppearanceItem>,
/// 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<crate::cmd::appearance::ActiveItem>,
pub(crate) after: Option<crate::cmd::appearance::ActiveItem>,
}
/// An interaction that a command from outside the tool set aside while it runs
/// ([`crate::Session::outside_interaction`]).
#[derive(Debug)]
+1 -1
View File
@@ -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;
+36
View File
@@ -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<String, serde_json::Map<String, Value>>,
/// 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(),
+192 -30
View File
@@ -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<Coords>,
@@ -202,11 +207,14 @@ pub(super) struct State {
editing: Cell<Option<Item>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
preset_limit: u64,
vars: variables::Handles,
tool: Cell<Option<&'static str>>,
}
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<Vec<NodeId>> {
/// 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<Rc<Vec<NodeId>>, HostError> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
return Ok(ids);
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes.iter().rev() {
@@ -627,9 +643,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
}
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<NodeId>, 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<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
}
/// The steps of [`on_doc`].
fn on_doc_steps<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before, layer, activated) = {
let s = h.session.borrow();
@@ -875,8 +910,8 @@ fn on_doc<T>(
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<T>(
{
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<T>(
r: std::result::Result<T, HostError>,
restored: std::result::Result<(), HostError>,
back: std::result::Result<(), HostError>,
) -> std::result::Result<T, HostError> {
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
/// <https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942> 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
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
@@ -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
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> 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<usize> {
(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<Doc, HostError> {
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<HostClass> {
("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<HostClass> {
]);
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<HostClass> {
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<HostClass> {
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<HostClass> {
]);
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<HostClass> {
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<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
+13 -11
View File
@@ -367,16 +367,18 @@ fn keeping_paint<T>(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<Vec<NodeId>> {
/// 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<Rc<Vec<NodeId>>, 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<Vec<NodeId>> =
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<u64> = 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::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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) {
+14 -11
View File
@@ -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<Vec<NodeId>> {
/// 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<Rc<Vec<NodeId>>, 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<NodeId> = 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<NodeId> = 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<Doc, HostError> {
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
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<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = 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::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
+1 -1
View File
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, 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::<u64>())?;
// 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());
+44 -2
View File
@@ -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<String>, 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<std::path::PathBuf, &'static str> {
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<std::path::PathBuf, &'static str> {
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);
+8
View File
@@ -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)
}
+17
View File
@@ -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;
+58
View File
@@ -219,6 +219,64 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
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<Vec<u8>, 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<std::fs::File> {
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<std::fs::File> {
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> {
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 {
+3
View File
@@ -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"),
+71
View File
@@ -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]
+29 -1
View File
@@ -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::<Vec<_>>());
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(), &params["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}");
let d = &s.doc().unwrap().doc;
let fills: Vec<Paint> = 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]
+10 -14
View File
@@ -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}");
+202 -1
View File
@@ -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::<Vec<_>>();
// 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<NodeId> = (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();
+18
View File
@@ -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);
+127
View File
@@ -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::<Vec<_>>()})).unwrap();
}
fn doc(s: &Session) -> Arc<Document> {
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<Document>) -> Option<Vec2> {
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);
}
+83 -32
View File
@@ -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<String> {
@@ -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#"<filter id="Glow7653"><feOffset dx="3" dy="3"/></filter>"#;
// 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]
+46
View File
@@ -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]
+42
View File
@@ -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();
+1
View File
@@ -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,
};
+43
View File
@@ -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();
+176 -18
View File
@@ -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<i64>| {
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: `<dir>/a\b.svg` is not the open `<dir>/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<bool> = 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`
+16 -35
View File
@@ -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::<Vec<_>>();
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('<k>2</k>').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("<rect").count() + svg.matches("<path").count(), 7, "{svg}");
let inspected = s.execute("document.inspect", &json!({})).unwrap();
assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(7));
let _ = std::fs::remove_file(&path);
}
#[test]
File diff suppressed because it is too large. Load diff
Loaded 100 of 282 files, more files were not shown because too many files have changed in this diff. Show more