Merge main into feat/color-randomly

This commit is contained in:
dotCooCoo committed 2026-12-01 01:04:32 -08:00
commit eadf345932
414 files changed
+28103 -3677

No files matched your search

+13 -6
View File
@@ -38,27 +38,32 @@
"applicability": "required"
},
{
"name": "gate / test 1/5 (ubuntu-24.04)",
"name": "gate / test 1/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 2/5 (ubuntu-24.04)",
"name": "gate / test 2/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 3/5 (ubuntu-24.04)",
"name": "gate / test 3/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 4/5 (ubuntu-24.04)",
"name": "gate / test 4/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 5/5 (ubuntu-24.04)",
"name": "gate / test 5/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 6/6 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
@@ -118,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]
+8 -33
View File
@@ -39,18 +39,19 @@ jobs:
dev-strip: true
# The workspace crates also build without line tables. A panic still names its file and line.
dev-debug: "0"
# Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates,
# and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)`
# passes only when all five did. On pushes to main, a `cache warm` leg builds what every
# shard builds and saves the dependency cache.
test-shards: 5
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
# saves the dependency cache.
test-shards: 6
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
# builds everything from source.
# cache-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: >-
@@ -58,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:
+27 -7
View File
@@ -7,9 +7,26 @@ on:
- "apps/vectorcraft/Cargo.toml"
- "apps/vectorcraft/src/printing.rs"
- "apps/vectorcraft/src/printing/**"
- "crates/ui-egui/Cargo.toml"
- "crates/ui-egui/src/print.rs"
- "crates/ui-egui/src/tests/printps.rs"
- ".github/workflows/print.yml"
# A push to main saves the Windows cache entry that pull requests restore.
push:
branches: [main]
paths:
- "Cargo.toml"
- "Cargo.lock"
- "apps/vectorcraft/Cargo.toml"
- "apps/vectorcraft/src/printing.rs"
- "apps/vectorcraft/src/printing/**"
- "crates/ui-egui/Cargo.toml"
- "crates/ui-egui/src/print.rs"
- "crates/ui-egui/src/tests/printps.rs"
- ".github/workflows/print.yml"
# A weekly run on main saves a fresh entry after a new stable Rust changes the cache key.
schedule:
- cron: "23 6 * * 1"
workflow_dispatch:
permissions:
contents: read
@@ -18,15 +35,14 @@ concurrency:
group: print-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
# but never save one; a manual run on main saves the cache they restore.
# Desktop printing on Windows, through the suite's shared gate. Pushes to main, the weekly run and
# manual runs on main save the cache; pull requests restore it and never save one.
windows:
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-2022"]'
# A change to Cargo.lock finds no cache (only main saves one) and builds everything cold:
# about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests.
# A run that finds no cache builds everything cold, which took 76 to 126 minutes.
timeout-minutes: 150
# As in ci.yml: test binaries without debug info or symbols, and workspace crates without
# line tables. A panic still names its file and line.
@@ -36,10 +52,14 @@ jobs:
craft-fonts-ref: ""
tools: ""
targets: ""
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
# Both test runs select the same two packages, so Cargo resolves features once and the
# second run reuses the first run's dependencies. The first runs every test of the app
# (`--bin vectorcraft --test it`), the second the UI crate's `tests::printps` tests. A filter
# that matches nothing still passes, so the printps run fails unless some test ran.
command: |
set -o pipefail
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
cargo test --locked -p vectorcraft
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --bin vectorcraft --test it
log="$RUNNER_TEMP/printps.log"
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
+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
+2
View File
@@ -42,6 +42,8 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
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 }}
+4 -1
View File
@@ -11,7 +11,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
@@ -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
+192 -194
View File
File diff suppressed because it is too large. Load diff
+53 -55
View File
@@ -4,53 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.24.1"
version = "0.25.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853", 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
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" }
@@ -86,7 +90,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
peniko = "0.6"
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
@@ -156,10 +159,8 @@ egui = "0.37"
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
clipboard-win = "5.4"
webbrowser = "1"
[workspace.lints.rust]
unsafe_code = "deny"
@@ -193,25 +194,22 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
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).
+31 -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
@@ -164,6 +164,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
+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",
]
+3
View File
@@ -211,6 +211,9 @@ fn main() -> ExitCode {
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
// The Language packs installed in the shared font store; `proof.installPack` returns once
// installed.
prefs_dir::use_language_packs();
let mut args: Vec<String> = std::env::args().skip(1).collect();
// Before any subcommand attaches the plug-in folder.
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
+3 -2
View File
@@ -20,14 +20,15 @@ vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] }
egui = { workspace = true }
egui_extras = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# Image loaders for `src/web.rs`, which builds only for wasm32.
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 = "610c86792a02aa3d416926ee44e3ec3788dea853", 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 }
+4
View File
@@ -5,6 +5,10 @@ dist = "../../dist/web"
public_url = "./"
filehash = true
[tools]
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
wasm_opt = "version_133"
[serve]
addresses = ["127.0.0.1"]
port = 8766
+1 -2
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 }
@@ -129,5 +130,3 @@ winresource = "0.1"
[dev-dependencies]
tempfile = "3"
# Bound socket buffers in real loopback transport deadline regressions.
socket2 = { 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"]));
}
}
+117 -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)]
@@ -571,6 +619,10 @@ fn main() -> std::process::ExitCode {
mac_fonts::install();
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
prefs_dir::install_fonts();
// Language packs: installs and index fetches run on their own threads, so the window keeps
// working while a pack downloads.
prefs_dir::use_language_packs();
vectorcraft_engine::packs::run_in_background(true);
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
@@ -691,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)
});
@@ -787,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),
@@ -804,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(),
@@ -812,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);
@@ -837,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.
@@ -883,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!(
+8
View File
@@ -24,6 +24,14 @@ pub fn install_fonts() {
}
}
/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font
/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the
/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not
/// VectorCraft's preferences.
pub fn use_language_packs() {
vectorcraft_engine::packs::use_font_store();
}
/// The folder `name` next to the settings, for what the user keeps: none in a run without
/// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing.
fn store_dir(name: &str) -> Option<PathBuf> {
+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)) {
+94 -19
View File
@@ -2,6 +2,7 @@
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
@@ -403,6 +404,8 @@ thread_local! {
thread_local! {
/// How many objects' drawn art [`drawn`] evaluated on this thread.
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many times [`has_own_effects`] read an object's effects on this thread.
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
@@ -446,6 +449,66 @@ impl Drop for InMask {
}
}
thread_local! {
/// While an [`InteriorProbe`] lives, whether a leaf tested without
/// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with
/// it; `None` outside a probe.
static INTERIOR_SEEN: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether
/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits
/// nothing then looks inside the unfilled closed paths with a second walk only when one of them
/// holds the point.
struct InteriorProbe {
was: Option<bool>,
}
impl InteriorProbe {
/// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths.
/// Otherwise the guard leaves things as they are, and no leaf measures an interior for it.
fn open(wanted: bool) -> Self {
Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } }
}
/// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point?
fn seen(&self) -> bool {
INTERIOR_SEEN.get() == Some(true)
}
}
impl Drop for InteriorProbe {
fn drop(&mut self) {
// A probe opened inside another passes what it saw on to it.
let seen = INTERIOR_SEEN.get() == Some(true);
INTERIOR_SEEN.set(self.was.map(|was| was || seen));
}
}
/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when
/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without
/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take
/// one with it, and hits nothing.
fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option<HitKind> {
if takes_interior(n, opt) {
return contains().then_some(HitKind::Fill);
}
if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) {
#[cfg(test)]
INTERIORS_PROBED.with(|c| c.set(c.get() + 1));
if contains() {
INTERIOR_SEEN.set(Some(true));
}
}
None
}
#[cfg(test)]
thread_local! {
/// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread.
static INTERIORS_PROBED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
/// the region it clips to. It is also under an [`InMask`] guard.
@@ -467,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
/// kept alone.
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
let f = DRAWN_ART.get()?;
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
return None;
}
let doc = symbols.document();
@@ -508,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { guide, .. } => !guide,
NodeKind::Compound { .. } => true,
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
_ => false,
}
}
@@ -667,10 +730,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
// an unfilled closed path ([`HitOptions::unfilled_interiors`]), when the first pass passes one
// holding `p` ([`InteriorProbe`]).
let painted = HitOptions { unfilled_interiors: false, ..opt };
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
let mut probe = Some(InteriorProbe::open(interiors));
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
if pass.unfilled_interiors && !probe.take().is_some_and(|probe| probe.seen()) {
break;
}
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
@@ -1017,12 +1085,15 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
/// only when the first, without it, hits nothing.
/// only when the first, without it, hits nothing and passes an unfilled closed path holding `p`
/// ([`InteriorProbe`]).
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline);
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() {
return painted;
}
drop(probe);
hit_test_walk(doc, p, opt, skip, editable_only)
}
@@ -1120,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
/// then can the registered [`ClipRegion`] find a geometry effect in it.
fn has_effects(clip: &Node) -> bool {
let mut found = false;
clip.walk(&mut |n| found |= has_own_effects(n));
found
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
}
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
let mut found = false;
n.walk(&mut |c| {
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
});
found
n.try_walk(&mut |c| {
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
})
.is_break()
}
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
fn has_own_effects(n: &Node) -> bool {
#[cfg(test)]
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
let visible = |e: &crate::Effect| e.visible;
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
}
@@ -1672,8 +1744,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let has_fill = n.appearance.has_visible_fill();
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed);
let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten();
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
@@ -1740,7 +1812,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
}
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p))
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -2121,11 +2193,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
find.find(&art.art, &mut path, None, outline).map(|_| path)
};
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only
// when the first walk passes one holding `p` ([`InteriorProbe`]).
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline);
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
if !opt.unfilled_interiors || opt.path_only || outline {
if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() {
return None;
}
drop(probe);
walk.restart();
pick(opt)
})
+147
View File
@@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
}
/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box
/// holds (50, 50), and it is drawn nowhere near that point.
fn open_corner(d: &mut Document, o: f64) -> Node {
let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)];
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false));
Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
}
/// How many leaves [`hit_leaf`] tested while `f` ran, with its result.
fn leaves_tested<R>(f: impl FnOnce() -> R) -> (R, usize) {
LEAVES_TESTED.with(|c| c.set(0));
let r = f();
(r, LEAVES_TESTED.with(std::cell::Cell::get))
}
/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the
/// document once: looking inside unfilled closed paths tests no more leaves than a click without
/// it. An unfilled closed path that holds the point is still hit inside.
#[test]
fn a_selection_click_that_hits_nothing_walks_the_document_once() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
for i in 0..10 {
let corner = open_corner(&mut d, f64::from(i));
d.insert(Some(l), 99, corner).unwrap();
}
let p = Point::new(50.0, 50.0);
let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING));
assert_eq!(hit, None);
assert_eq!(without, 10);
let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS));
assert_eq!(hit, None);
assert_eq!(with, without, "hit_test");
let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None));
assert!(tops.is_empty());
assert_eq!(with, without, "objects_at");
// An unfilled frame below them that holds the point: the second walk finds it.
let frame = d.alloc_id();
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame));
assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]);
}
/// A hit test that does not look inside unfilled closed paths measures none of their interiors.
#[test]
fn a_hit_test_without_unfilled_interiors_measures_no_interior() {
let mut d = Document::new(200.0, 200.0);
stroked(&mut d, &FRAME, true);
let p = Point::new(50.0, 50.0);
let probed = |f: &dyn Fn()| {
INTERIORS_PROBED.with(|c| c.set(0));
f();
INTERIORS_PROBED.with(std::cell::Cell::get)
};
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test");
assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at");
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only");
assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside");
}
/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no
/// unfilled closed path of the art holds the point, walks the art once.
#[test]
fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() {
let mut d = Document::new(200.0, 200.0);
let corners: Vec<Arc<Node>> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect();
let root = Node::group(d.alloc_id(), corners);
d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) });
let l = d.layers[0].id;
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let n = d.node(inst).unwrap();
let p = Point::new(50.0, 50.0);
let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING));
assert_eq!(part, None);
assert!(without >= 10, "{without} leaves tested");
let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS));
assert_eq!(part, None);
assert_eq!(with, without);
}
#[test]
fn long_plain_stroke_hits_its_middle_and_curved_end() {
let mut d = Document::new(200.0, 200.0);
@@ -3569,3 +3651,68 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
}
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
/// once.
#[test]
fn hovers_past_plain_paths_read_each_paths_effects_once() {
set_drawn_art(shifted_art);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let paths = 100;
for i in 0..paths {
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
d.insert(Some(l), 0, n).unwrap();
}
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
let before = reads();
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
let read = reads() - before;
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
}
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
/// object found with one: the members after it are not read.
#[test]
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
set_clip_region(moved_clip_region);
set_drawn_art(shifted_art);
let mut d = Document::new(1000.0, 1000.0);
let members: Vec<_> = (0..100)
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
.collect();
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
mask.appearance.effects.push(test_move());
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
let before = reads();
assert!(has_effects(&mask));
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
let symbols = d.symbol_boxes();
let before = reads();
assert!(draws_effects(&symbols, &mask));
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
}
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
#[test]
fn hovers_past_many_paths_read_their_anchors_once() {
use vectorcraft_geom::anchors::measured_control_anchors;
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
for i in 0..100 {
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
d.insert(Some(l), 0, n).unwrap();
}
let empty = Point::new(900.0, 900.0);
let before = measured_control_anchors();
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = measured_control_anchors() - before;
assert!(first >= 400, "the first hover reads every square's anchors: {first}");
for _ in 0..3 {
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
}
assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor");
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
}
+1 -9
View File
@@ -308,16 +308,8 @@ fn resolve_kids(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> Vec<(usize, Arc<Node>)> {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
let mut out = vec![];
for (i, c) in kids.iter().enumerate() {
let o = old.and_then(|old| match old.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
});
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
continue;
}
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
let mut c = c.clone();
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
out.push((i, c));
+1
View File
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::changed_nodes;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
+4
View File
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
use crate::text::TextObject;
mod attributes;
mod changed;
mod clip;
mod extras;
mod ids;
@@ -25,6 +26,9 @@ mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
#[cfg(test)]
pub(crate) use changed::COUNTERPART_LOOKUPS;
pub use changed::changed_nodes;
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+33
View File
@@ -0,0 +1,33 @@
use std::collections::HashMap;
use super::{Arc, Node, NodeId};
#[cfg(test)]
thread_local! {
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
/// node is new). A node that is the same node as the one at its position in `before` is skipped
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
after.iter().enumerate().filter_map(move |(i, a)| {
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
#[cfg(test)]
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
Some((i, a, b))
})
}
+34
View File
@@ -949,3 +949,37 @@ fn try_walk_ends_at_the_break() {
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
}
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
/// the same nodes in the same places are passed over by their pointers.
#[test]
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
let mut after = before.clone();
let mut edited = (*after[500]).clone();
edited.name = Some("edited".into());
after[500] = Arc::new(edited);
after.push(leaf(5000));
COUNTERPART_LOOKUPS.with(|c| c.set(0));
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
}
/// A node that moved to another place in the list is paired with itself by its id and left out
/// when it is the same node; a changed node that moved is paired with its old node, and a node
/// that is gone from the list gives nothing.
#[test]
fn changed_nodes_pairs_moved_nodes_by_id() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
let mut edited = (*before[0]).clone();
edited.locked = true;
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
assert_eq!(changed_nodes(&[], &after).count(), 3);
}
+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)
+20 -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
@@ -89,6 +90,10 @@ windows-native-keyring-store = "1.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { version = "1.12", optional = true }
# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in
# Cargo.lock (craft-font-manager), so this adds no new crate.
craft-font-store = { workspace = true }
craft-font-catalog = { workspace = true }
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
# Linux. All MIT OR Apache-2.0.
@@ -112,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"] }
@@ -139,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",
]
+27 -1
View File
@@ -65,6 +65,8 @@ pub(crate) mod objects_on_path;
mod opacitymask;
mod overprint;
pub mod package;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
mod paint;
mod panelcmds;
pub mod params;
@@ -109,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;
@@ -325,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());
@@ -382,6 +386,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
// Language packs need a font store, which the web build has none of.
#[cfg(not(target_arch = "wasm32"))]
v.extend(packs::specs());
v.extend(svgfilter::specs());
v.extend(newart::specs());
v.extend(colortheme::specs());
@@ -672,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).
@@ -869,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};
+223 -7
View File
@@ -1,8 +1,10 @@
//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
@@ -17,7 +19,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
@@ -52,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
grid
),
cmd!(
"addon.arrange.offset",
"Offset Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}",
has_multi,
offset
),
cmd!(
"addon.arrange.swap",
"Swap Objects",
@@ -79,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
size
),
cmd!(
"addon.arrange.match",
"Match Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
has_multi,
match_objects
),
cmd!(
"addon.arrange.groupOverlapping",
"Group Overlapping Objects",
@@ -167,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
})
}
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
s.note_journal("scaleStrokes", json!(on));
Ok(on)
}
/// The box of object `id` as `object.setBounds` measures it.
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
@@ -228,10 +256,46 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "count": n }))
}
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.offset";
let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?;
let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position";
let reverse = switch_or(p, "reverse", false, C)?;
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
// The objects in stacking order from the back, each with its leading and trailing edge along the direction.
let mut items: Vec<(NodeId, f64, f64)> = roots
.iter()
.filter_map(|id| {
let b = effects::preview::bounds_of(d, &[*id], true)?;
Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) })
})
.collect();
if by_position {
items.sort_by(|a, b| a.1.total_cmp(&b.1));
}
if reverse {
items.reverse();
}
// The first stays; each later one starts `gap` past where the one before it now ends.
let mut end: Option<f64> = None;
let xfs: Vec<(NodeId, Affine)> = items
.iter()
.map(|&(id, start, finish)| {
let shift = end.map_or(0.0, |e| e + gap - start);
end = Some(finish + shift);
(id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }))
})
.collect();
transform_each(s, "Offset Objects", false, &xfs)?;
Ok(json!({ "count": items.len() }))
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let roots = selected_roots(s)?;
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
@@ -244,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.replace";
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let keep = switch_or(p, "keep", false, C)?;
let roots = selected_roots(s)?;
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
@@ -295,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
}
let proportional = switch_or(p, "proportional", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
if let Some(w) = width {
q["width"] = json!(w);
@@ -313,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "count": xfs.len() }))
}
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
let st = s.doc()?;
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
Some("bottom") => roots.first().copied(),
Some(_) => roots.last().copied(),
None => key.or_else(|| roots.last().copied()),
};
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
}
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
let paths = d.index_paths(targets.iter().copied().chain([source]));
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
}
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.match";
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
let rotate = switch_or(p, "rotate", false, C)?;
let stacking = switch_or(p, "stacking", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
if size == "none" && !rotate && !stacking {
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
}
let roots = selected_roots(s)?;
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let source = match_source(s, p, &roots, C)?;
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
if targets.is_empty() {
return Err(bad(C, "select at least two objects"));
}
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
let (w, h) = if size == "none" {
(0.0, 0.0)
} else {
let sb = box_of(s, source)?;
(sb.rect.width(), sb.rect.height())
};
let wanted = match size {
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
"width" => Some(json!({ "width": w, "proportional": true })),
"height" => Some(json!({ "height": h, "proportional": true })),
"both" => Some(json!({ "width": w, "height": h })),
_ => None,
};
let angle = s.doc()?.doc.bbox_angle(&[source]);
let mut xfs = Vec::with_capacity(targets.len());
for &id in &targets {
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
let Some(b) = s.transform_box(&[id]) else {
if wanted.is_some() {
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
}
if turn.abs() > 1e-9 {
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
}
continue;
};
let mut xf = Affine::IDENTITY;
if let Some(q) = &wanted {
let mut q = q.clone();
q["reference"] = json!(reference);
q["strokes"] = json!(strokes);
xf = object_bounds_transform(s, &q, id)?;
}
if turn.abs() > 1e-9 {
// Rotation uses the reference point that sizing keeps in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
}
if wanted.is_some() {
let sc = scaling(s, &json!({ "strokes": strokes }));
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let measure = |xf| {
d.node(id).and_then(|n| {
let mut n = n.clone();
transform_node(&mut n, xf, sc, true);
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
})
};
let misses = |measured: Option<Rect>| {
measured.is_none_or(|r| match size {
"width" => (r.width() - w).abs() > 1e-6,
"height" => (r.height() - h).abs() > 1e-6,
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
})
};
// The sized and turned object, measured in its final frame, must have the size asked for.
if misses(measure(xf)) {
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
}
}
xfs.push((id, xf));
}
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
xfs.retain(|(_, xf)| !still(xf));
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
let (mut placed, mut left) = (vec![], vec![]);
if restack {
let d = &s.doc()?.doc;
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
let is_clip =
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
if targets.iter().any(is_clip) {
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
}
let parent = d.parent_of(source);
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
left = crate::cmd::intertwine::groups_of(d, &targets);
}
let count = json!({ "source": source.0, "count": targets.len() });
if xfs.is_empty() && !restack {
return Ok(count);
}
let q = json!({ "strokes": strokes, "patterns": patterns });
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &q);
sc.patterns = transform_patterns(s, &q, &ids)?;
s.edit("Match Objects", |d, _| {
for (id, xf) in &xfs {
if let Some(n) = d.node_mut(*id) {
transform_node(n, *xf, sc, true);
}
}
if restack {
let moved = d.remove_many(&targets)?;
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
// Targets moved out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
}
Ok(())
})?;
Ok(count)
}
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
/// open where each one starts are compared with it.
@@ -459,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
let distribute = switch_or(p, "distribute", false, C)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let ids = checked_ids_or_selection(s, p, C)?;
if ids.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
@@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() {
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
}
#[test]
fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() {
let mut s = session();
let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0);
let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0);
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[c, a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap();
assert_eq!(r["count"], json!(3));
assert_eq!(steps(&s), n + 1, "one undo step");
// From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y.
assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0)));
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)));
// Reversed: c stays, then b, then a. The gap defaults to 10.
s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap();
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
}
#[test]
fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() {
let mut s = session();
let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0);
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0);
select(&mut s, &[a, b, c]);
// Top to bottom: b, c, a; each 5 into the one before it, keeping its x.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap();
assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// Bottom to top: a stays, then c, then b.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
// Left to right in a row: a, b, c.
s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// Visual boxes 24 wide, touching.
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
// A 200 wide object clipped to a 30 wide mask at x 100.
let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0);
let mask = rect(&mut s, 100.0, 40.0, 30.0, 30.0);
select(&mut s, &[clipped, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0];
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, group, c]);
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// The mask starts at a's right edge, and c at the mask's.
assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask));
assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped));
assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.offset"), "off with one object");
select(&mut s, &[a, b]);
assert!(enabled(&s, "addon.arrange.offset"));
// Already 10 apart in a row.
let n = steps(&s);
s.execute("addon.arrange.offset", &json!({})).unwrap();
assert_eq!(steps(&s), n, "no step when nothing moves");
// Two objects in one group are one object: nothing to chain.
s.execute("object.group", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
assert!(!enabled(&s, "addon.arrange.offset"), "off with one group");
refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]);
s.execute("edit.undo", &json!({})).unwrap();
let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
select(&mut s, &[a, b]);
refuses(
&mut s,
"addon.arrange.offset",
&[
json!({"direction": "diagonal"}),
json!({"direction": 1}),
json!({"gap": 1e7}),
json!({"gap": -1e7}),
json!({"gap": "10"}),
json!({"order": "size"}),
json!({"reverse": "yes"}),
],
);
}
#[test]
fn swap_trades_places_and_optionally_sizes() {
let mut s = session();
@@ -215,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
}
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
/// (100, 100) and `c` 10 × 30 at (200, 0).
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
select(s, &[a, b, c]);
(a, b, c)
}
#[test]
fn match_gives_the_others_the_key_objects_size() {
let mut s = session();
let (a, b, c) = three(&mut s);
s.execute("select.key", &json!({"id": b.0})).unwrap();
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(r, json!({"source": b.0, "count": 2}));
assert_eq!(steps(&s), n + 1, "one undo step");
// About each center; the key object stays.
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
// The width, with the height in proportion, about the top-left corner.
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
}
#[test]
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
let mut s = session();
let (a, b, c) = three(&mut s);
// No key object: the frontmost, c.
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(r["source"], json!(c.0));
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
assert_eq!(r["source"], json!(a.0));
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
// "top" names the frontmost even while a key object is set.
s.execute("select.key", &json!({"id": a.0})).unwrap();
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
assert_eq!(r["source"], json!(c.0));
}
#[test]
fn match_turns_the_others_to_the_sources_angle() {
let mut s = session();
let (a, b, c) = three(&mut s);
select(&mut s, &[b]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
select(&mut s, &[a, b, c]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
let n = steps(&s);
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
let o = s.transform_box(&[id]).unwrap();
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
let at = o.center();
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
}
// Turned back to the angle of an unturned source.
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, d]);
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
}
#[test]
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
for size in ["width", "height", "both"] {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[target]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
assert_eq!(r, json!({"source": source.0, "count": 1}));
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
for angle in [0, 30] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[a]);
s.execute("edit.clear", &json!({})).unwrap();
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
select(&mut s, &[b]);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.transform_box(&[target]).is_none());
assert!(s.transform_box(&[source]).is_none());
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
if angle == 0 {
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
} else {
let error = result.unwrap_err().to_string();
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn match_puts_the_others_directly_above_the_source() {
let mut s = session();
let (a, b, c) = three(&mut s);
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[d, a, c]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
let n = steps(&s);
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "already above it: no step");
// An object in another layer goes into the source's.
s.execute("layer.new", &json!({})).unwrap();
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
select(&mut s, &[b, e]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(layer_order(&s), [a, c, d, b, e]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_order(&s), [a, c, d, b]);
}
#[test]
fn match_makes_no_step_when_everything_matches() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
select(&mut s, &[a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
assert_eq!(r["count"], json!(1));
assert_eq!(steps(&s), n, "the same size and angle: no step");
}
#[test]
fn match_turns_the_others_about_their_reference_point() {
let mut s = session();
let (a, b, c) = three(&mut s);
select(&mut s, &[b]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
select(&mut s, &[a, b, c]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
// Each top-left corner stays where it was.
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
let o = s.transform_box(&[id]).unwrap();
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
}
}
#[test]
fn match_scales_strokes_as_asked() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
}
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
s.execute(cmd, &p).unwrap();
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
}
#[test]
fn match_stacking_leaves_a_clipping_path_in_place() {
let mut s = session();
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
select(&mut s, &[art, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
select(&mut s, &[mask, x]);
s.execute("select.key", &json!({"id": x.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
}
#[test]
fn match_size_refuses_a_target_with_no_width() {
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
// Its height can still take the source's.
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
}
#[test]
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[line]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
select(&mut s, &[b]);
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[line]).unwrap().rect;
let wanted = s.transform_box(&[b]).unwrap().rect;
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
select(&mut s, &[b]);
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
}
#[test]
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
select(&mut s, &[a, b]);
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, c]);
s.execute("select.key", &json!({"id": c.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
let d = &s.doc().unwrap().doc;
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
let e = d.node(a).unwrap().extras();
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
}
#[test]
fn match_stacking_needs_no_bounds_on_the_source() {
let mut s = session();
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
select(&mut s, &[b, g]);
s.execute("select.key", &json!({"id": g.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
}
#[test]
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
select(&mut s, &[source, b]);
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[a]);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.transform_box(&[source]).is_none());
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
select(&mut s, &[c, d]);
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
assert!(error.contains("can't be intertwined"), "{error}");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
}
#[test]
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn match_refuses_bad_params() {
let mut s = session();
let (a, _, _) = three(&mut s);
refuses(
&mut s,
"addon.arrange.match",
&[
json!({}),
json!({"size": "none"}),
json!({"size": "area"}),
json!({"size": 1}),
json!({"rotate": 1}),
json!({"stacking": "yes"}),
json!({"size": "both", "reference": 9}),
json!({"size": "both", "reference": 1.5}),
json!({"size": "both", "source": "left"}),
json!({"size": "both", "scaleStrokes": "no"}),
json!({"size": "both", "patterns": 0}),
],
);
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
assert!(e.contains("no key object"), "{e}");
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
}
#[test]
fn bad_params_are_refused() {
let mut s = session();
@@ -261,6 +777,7 @@ fn off_without_a_selection() {
"addon.arrange.swap",
"addon.arrange.replace",
"addon.arrange.size",
"addon.arrange.match",
"addon.arrange.groupOverlapping",
"addon.arrange.randomizeOpacity",
"addon.arrange.sort",
+2 -9
View File
@@ -14,7 +14,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
@@ -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)?;
+4 -4
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
),
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); values the symbol already has, newName included, change nothing and add no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_doc,
symbol_options
),
@@ -289,7 +289,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Symbol",
[],
None,
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}",
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them; when every instance already shows the symbol, nothing changes and no undo step is recorded) → {ids}",
has_selection,
symbol_replace
),
+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 }))
+8 -11
View File
@@ -347,13 +347,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let dynamic = type_param(p, C)?;
let pixel = pixel_grid_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
match pixel {
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
Some(_) => {}
}
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() && pixel.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid"));
}
if let Some(ref n) = new_name
&& n != &name
@@ -362,7 +357,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("a symbol named `{n}` already exists")));
}
let final_name = new_name.clone().unwrap_or_else(|| name.clone());
s.edit("Symbol Options", |d, _| {
// Values the symbol already has leave the document as it is, and no undo step is added.
crate::cmd::colorcmds::edit_if_changed(s, "Symbol Options", |before, d| {
if let Some(ref n) = new_name
&& n != &name
{
@@ -439,7 +435,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = pixel {
d.set_symbol_pixel_aligned(&final_name, on);
}
Ok(())
Ok(((), before != &*d))
})?;
Ok(options_json(&s.doc()?.doc, &final_name))
}
@@ -859,7 +855,8 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
s.edit("Replace Symbol", |d, _| {
// Instances that already show the symbol leave the document as it is, and no undo step is added.
crate::cmd::colorcmds::edit_if_changed(s, "Replace Symbol", |before, d| {
let new = natural_size(d, &name);
for id in &ids {
let (old, other) = match d.node(*id).map(|n| &n.kind) {
@@ -877,7 +874,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
}
}
fit_overrides(d, &ids);
Ok(())
Ok(((), ids.iter().any(|id| before.node(*id) != d.node(*id))))
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
+2 -1
View File
@@ -920,7 +920,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result<Anchor> {
};
let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?);
match v.get("smooth").filter(|b| !b.is_null()) {
None | Some(Value::Bool(false)) => {}
None => {}
Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner,
Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth,
Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")),
}
+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> {
+27 -17
View File
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
/// computer's when `None`).
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
let fonts: Vec<Value> = missing_fonts(&st.doc)
let fonts = missing_font_rows(&st.doc);
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
if let Some(dir) = fonts_next_to_document(st, rules) {
out["fontsNextToDocument"] = json!(dir);
}
out
}
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
missing_fonts(d)
.into_iter()
.map(|m| {
json!({
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
})
})
.collect();
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
.collect()
}
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
/// `rules` (this computer's when `None`).
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
// is made absolute against the working folder when the document's path is relative. It is
// offered when a search may start there, as far as the rules tell without listing a folder.
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
};
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
out["fontsNextToDocument"] = json!(dir);
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
}
out
};
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
}
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
+211 -18
View File
@@ -194,6 +194,51 @@ impl Options {
/// Outlines with their layer colours ([`highlights`]).
pub type Outlines = Vec<(BezPath, [u8; 3])>;
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
/// allocation back until the outlines are found again.
#[derive(Debug, Default, PartialEq)]
pub struct Highlights {
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
/// it stroked for these outlines while the number stays the same.
pub revision: u64,
/// The outlines in each layer color, the colors in the order of their first outline.
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
}
/// The [`Highlights::revision`] the next set of outlines takes.
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
impl Highlights {
/// `outlines` grouped by color, under a new revision.
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
if outlines.is_empty() {
return NO_HIGHLIGHTS.clone();
}
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
for (path, color) in outlines {
match groups.iter_mut().find(|(c, _)| *c == color) {
Some((_, paths)) => paths.push(path),
None => groups.push((color, vec![path])),
}
}
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
}
/// How many outlines there are, in every color.
pub fn len(&self) -> usize {
self.groups.iter().map(|(_, paths)| paths.len()).sum()
}
/// Whether there is no outline.
pub fn is_empty(&self) -> bool {
self.groups.iter().all(|(_, paths)| paths.is_empty())
}
}
/// A Global Edit in progress (per document; not saved, not an undo step).
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
@@ -202,7 +247,7 @@ pub struct GlobalEdit {
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
}
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
@@ -222,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 {
@@ -482,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;
}
@@ -1017,47 +1066,191 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
/// ([`similar`]).
pub fn highlights(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
let Some(ge) = &st.global_edit else { return similar(s) };
if let Some((rev, out)) = &*ge.outlines.borrow()
&& *rev == st.revision
{
return out.clone();
}
let out = outlines(st, &ge.members);
let out = Highlights::new(outlines(st, &ge.members));
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
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, Outlines)>>;
/// [`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.
pub fn similar(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
return vec![];
/// 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() };
// 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 = match matches(s, o) {
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 {
+175 -2
View File
@@ -6,7 +6,8 @@
//! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
//! and a change of selection loads only the proxies. `paint.default` resets it.
//! and a change of selection loads only the proxies. `paint.default` resets it, and
//! `appearance.setNewArt` sets its fill, stroke and stroke options whatever is selected.
//!
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
@@ -34,7 +35,7 @@ pub(crate) struct NewArtSource {
use super::gradient::unplaced;
use super::paint::SelectionPaints;
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or};
use crate::doc_state::{SelectionRecord, objects_only};
pub fn specs() -> Vec<CommandSpec> {
@@ -57,9 +58,181 @@ pub fn specs() -> Vec<CommandSpec> {
always,
describe
),
cmd!(
"appearance.setNewArt",
"Set New Art Appearance",
[],
None,
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
always,
set_new_art
),
]
}
/// The most dash and gap lengths `appearance.setNewArt` takes.
const MAX_DASHES: usize = 64;
/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes.
const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"];
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
/// What [`dash_fault`] finds wrong with a list of dash and gap lengths.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum DashFault {
/// More than [`MAX_DASHES`] lengths.
TooMany,
/// A length that is not a number from 0 to [`MAX_DASH_LENGTH`].
OutOfRange,
/// Lengths that are all 0.
AllZero,
}
/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the
/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good.
/// An empty list (a solid line) is good.
pub(crate) fn dash_fault(lengths: &[f64]) -> Option<DashFault> {
if lengths.len() > MAX_DASHES {
Some(DashFault::TooMany)
} else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) {
Some(DashFault::OutOfRange)
} else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) {
Some(DashFault::AllZero)
} else {
None
}
}
/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of
/// the document in front.
pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color {
super::paint::new_color(s, &json!({}), c)
}
/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before
/// anything changes.
fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.setNewArt";
let paint = |key: &str, fill: bool| -> Result<Option<Paint>> {
let Some(v) = p.get(key) else { return Ok(None) };
if !v.is_object() {
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
}
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) {
return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", "))));
}
if v.get("swatch").is_some_and(|w| !w.is_string()) {
return Err(bad(C, format!("{key}: `swatch` must be a swatch name")));
}
let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some());
if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) {
return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`")));
}
let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?;
if !fill && matches!(&given, Paint::Gradient(g) if g.gradient.dither) && v.get("swatch").and_then(Value::as_str).is_none() {
return Err(bad(C, "`dither` applies to gradient fills"));
}
Ok(Some(unplaced(&given)))
};
let (fill, stroke) = (paint("fill", true)?, paint("stroke", false)?);
let number = |key: &str, min: f64, max: f64| -> Result<()> {
match p.get(key) {
None => Ok(()),
Some(v) if v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n)) => Ok(()),
Some(v) => Err(bad(C, format!("{key} must be a number from {min} to {max}, got {v}"))),
}
};
number("weight", 0.0, 1000.0)?;
number("miterLimit", 1.0, 500.0)?;
number("dashOffset", -MAX_DASH_LENGTH, MAX_DASH_LENGTH)?;
for key in ["cap", "join"] {
if p.get(key).is_some_and(|v| !v.is_string()) {
return Err(bad(C, format!("{key} must be a name")));
}
}
match p.get("dash") {
None | Some(Value::Null) => {}
Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
Some(Value::Array(a)) => {
let lengths: Option<Vec<f64>> = a.iter().map(Value::as_f64).collect();
match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) {
None => {}
Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))),
Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")),
}
}
Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))),
}
let flag = |key: &str| -> Result<Option<bool>> {
p.get(key).map(|v| v.as_bool().ok_or_else(|| bad(C, format!("{key} must be true or false, got {v}")))).transpose()
};
let (fill_overprint, stroke_overprint) = (flag("fillOverprint")?, flag("strokeOverprint")?);
let options: serde_json::Map<String, Value> =
["weight", "cap", "join", "miterLimit", "dash", "dashOffset"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect();
let change = super::stroke::StrokeChange::parse(&Value::Object(options), C)?;
let dashed = match p.get("dash") {
Some(Value::Array(a)) => !a.is_empty(),
Some(_) => false,
None => s.new_art().stroke().is_some_and(|st| st.dash.is_some()),
};
if p.get("dashOffset").and_then(Value::as_f64).is_some_and(|o| o != 0.0) && !dashed {
return Err(bad(C, "dashOffset needs a dash pattern"));
}
let nothing = fill.is_none() && stroke.is_none() && change.is_empty() && fill_overprint.is_none() && stroke_overprint.is_none();
if !nothing
&& !s.prefs.new_art_basic
&& !(s.tool_paints(false) && s.tool_paints(true))
&& s.active().is_some_and(|st| !st.selection.subjects().is_empty())
{
return Err(bad(
C,
"with New Art Has Basic Appearance off, new art takes the selected object's appearance: deselect it or turn the option on",
));
}
let look = |s: &Session| {
let (opacity, blend, style) = s.new_art_transparency();
(s.new_art(), opacity, blend, style.map(str::to_string))
};
let (before, was) = (s.paint.clone(), look(s));
if let Some(f) = fill {
s.paint.fill = f;
}
if let Some(st) = stroke {
if !st.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
s.paint.stroke_width = 1.0;
}
s.paint.stroke = st;
}
if let Some(w) = change.weight {
s.paint.stroke_width = w;
}
if !change.is_empty()
&& let Some(st) = s.new_art_stroke_mut()
{
change.apply(st);
}
if let Some(on) = fill_overprint {
let t = s.new_art_template_mut();
if t.fill().is_none() {
t.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::None)));
}
if let Some(f) = t.fill_mut() {
f.overprint = on;
}
}
if let Some(on) = stroke_overprint
&& let Some(st) = s.new_art_stroke_mut()
{
st.overprint = on;
}
let changed = look(s) != was;
if !changed {
s.paint = before;
}
Ok(json!({ "changed": changed }))
}
/// `t` reduced to a basic appearance: an empty fill under its top stroke (options kept, without
/// its own transparency or effects).
fn basic_of(t: &Appearance) -> Appearance {
+96 -20
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
),
@@ -180,8 +180,9 @@ pub struct DocSettings {
pub layout: ArtboardLayout,
/// Columns of a grid layout.
pub columns: u32,
/// Rows of a grid by column, in place of `columns` when more than 0.
#[serde(skip_serializing_if = "is_zero")]
/// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a
/// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`).
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
pub rows: u32,
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
/// outside that range is read as the nearer end).
@@ -380,12 +381,25 @@ impl DocSettings {
return Ok(());
}
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32);
for (k, v) in o {
match k.as_str() {
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
"columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?,
"rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?,
"columns" => {
self.columns = v
.as_f64()
.filter(|c| c.is_finite() && *c >= 1.0)
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
.round()
.min(MAX_ARTBOARDS as f64) as u32
}
"rows" => {
self.rows = v
.as_f64()
.map(f64::round)
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
.map(|r| r as u32)
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
}
"spacing" => {
self.spacing = v
.as_f64()
@@ -590,6 +604,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
}
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
/// place) stays 0.
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
@@ -976,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();
@@ -1002,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
@@ -1025,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
@@ -1066,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);
}
}
@@ -1099,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 }))
}
@@ -1114,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
),
+15 -19
View File
@@ -5,7 +5,7 @@
use std::collections::HashMap;
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
use super::{
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
@@ -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.
@@ -226,15 +238,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
/// mask art holds such instances (`masked`).
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
masked.push(a.id);
}
@@ -423,15 +427,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
out.push(a.id);
} else if let Some(children) = a.children() {
+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);
+3 -11
View File
@@ -25,12 +25,12 @@
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
//! the objects that move up the path after it; Expand).
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Rect;
use super::edit::{roots_of, selected_roots};
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
/// (`before`: the same list before the edit), outer ones first.
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if is_objects_on_path(a) {
out.push(a.id);
}
+52 -9
View File
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency Info",
[],
None,
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none); editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none). Without ids or id, with an object of a dynamic symbol instance selected by Direct Selection, opacity and blend are that object's for this instance, as transparency.set changes them; editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
has_doc,
info
),
@@ -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,14 +498,26 @@ 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> {
let st = s.doc()?;
let ids = transparency_targets(s, p)?;
// The points `transparency.set` with the same `ids` (or none) fades.
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
// Without `ids` or `id`, the values `transparency.set` without them edits: those of the panel,
// whose picked mesh points and selected dynamic symbol part take the opacity (and the part the
// blend mode).
let i = if p.get("ids").is_none() && p.get("id").is_none() {
s.transparency_info()
} else {
let ids = transparency_targets(s, p)?;
let points = super::paint::picked_mesh_points_of(s, &ids);
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
};
Ok(json!({
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
"opacity": i.opacity,
@@ -753,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");
}
}
+117
View File
@@ -0,0 +1,117 @@
//! Language packs as commands (#4936): list, install and remove the packs that spell-check and
//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn
//! downloading on: an install needs the Craft apps' shared download setting, which only the person
//! using an app turns on.
use serde_json::{Value, json};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
use crate::packs::{self, Outcome};
/// The Language pack commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "proof.packs",
"Language Packs",
[],
None,
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
always,
list
),
cmd!(
query "proof.installPack",
"Install Language Pack",
[],
None,
"{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}",
always,
install
),
cmd!(
query "proof.removePack",
"Remove Language Pack",
[],
None,
"{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}",
always,
remove
),
]
}
fn locale_param(p: &Value, command: &str) -> Result<String> {
let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?;
packs::parse_locale(raw).map_err(|e| bad(command, e))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "proof.packs";
match p.get("refresh") {
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) => {
not_confined(C)?;
packs::refresh().map_err(EngineError::Other)?;
}
Some(_) => return Err(bad(C, "`refresh` must be true or false")),
}
// The jobs before the installed packs: an install makes craft-proof read its pack before it
// leaves the jobs, so one that ends between the two reads is in one list or the other.
let packs::Status { installing, refreshing, errors } = packs::status();
let installed = craft_proof::packs::installed();
let backend = packs::backend();
let rows: Vec<Value> = packs::available()
.iter()
.map(|p| {
json!({
"locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class,
"spelling": p.spelling, "hyphenation": p.hyphenation,
"installed": installed.iter().any(|i| i.locale == p.locale),
})
})
.collect();
// An install that ended since the last frame shows in every document's layout.
s.poll_language_packs();
Ok(json!({
"packs": rows,
"installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::<Vec<_>>(),
"installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::<Vec<_>>(),
"refreshing": refreshing,
"errors": errors,
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
"available": backend.is_some(),
}))
}
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
/// store the Craft apps share, which is outside them.
fn not_confined(command: &str) -> Result<()> {
if crate::file_access::current().is_some() {
return Err(EngineError::Other(format!(
"automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots"
)));
}
Ok(())
}
fn install(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.installPack")?;
not_confined("proof.installPack")?;
match packs::install(&locale).map_err(EngineError::Other)? {
Outcome::Started => Ok(json!({"locale": locale, "started": true})),
Outcome::Done => {
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": true}))
}
}
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.removePack")?;
not_confined("proof.removePack")?;
packs::remove(&locale).map_err(EngineError::Other)?;
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": false}))
}
+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,
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Anchors",
[],
None,
"{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry",
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry",
has_doc,
set_anchors
),
+18 -6
View File
@@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- queries ----------
/// The colour mode an image file stores its pixels in.
fn color_mode(bytes: &[u8]) -> &'static str {
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
_ => "RGB",
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
/// and the Properties panel ask `image.info` again after every change, each step of a drag
/// included. A file in another format is decoded.
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
match craft_image_codecs::inspect_raster(bytes) {
Ok(Some(i)) => match i.color_type {
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
T::Cmyk | T::CmykAlpha => "CMYK",
_ => "RGB",
},
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
Some(L::Gray | L::GrayA) => "Grayscale",
Some(L::Cmyk | L::CmykA) => "CMYK",
_ => "RGB",
},
}
}
+3
View File
@@ -1914,6 +1914,9 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
// Only native builds load modules, so only they save the disabled list.
#[cfg(target_arch = "wasm32")]
let _ = (s, turn);
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
+2
View File
@@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[
"text.rescanFonts",
"text.fontList",
"text.spelling.",
// Language packs: downloads into, and removals from, the font store the Craft apps share.
"proof.",
"colorTheme.",
"magicWand.",
"eyedropper.",
@@ -6,6 +6,8 @@
pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.match",
"addon.arrange.offset",
"addon.arrange.randomizeOpacity",
"addon.arrange.replace",
"addon.arrange.size",
@@ -82,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",
@@ -105,6 +108,7 @@ pub(super) const ALLOWED: &[&str] = &[
"appearance.removeItem",
"appearance.setActiveItem",
"appearance.setItem",
"appearance.setNewArt",
"appearance.showAllHidden",
"appearance.targetContents",
"appearance.transfer",
@@ -407,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() {
+3 -14
View File
@@ -6,12 +6,9 @@ use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
};
use serde_json::{Value, json};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
};
use std::{collections::BTreeMap, sync::Arc};
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
use vectorcraft_pathops as po;
use vectorcraft_tools::builder::{self as b, BuilderMap};
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
}
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().shaper.is_some() {
out.push(a.id);
}
+4 -3
View File
@@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize
/// not, since a save takes in the words another window saved), and a dictionary file attached.
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
/// out of date (Auto Spell Check checks the type again).
/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of
/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with
/// craft-proof's own dictionaries, which change when a Language pack is installed or removed.
pub fn dictionary_generation() -> u64 {
DICTIONARY_GENERATION.load(Ordering::Relaxed)
DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation())
}
fn dictionary_changed() {
+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)]
+6 -1
View File
@@ -12,6 +12,8 @@ pub mod guard;
pub mod inspect;
pub mod journal;
pub mod link_watch;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
pub mod schemas;
pub mod steps;
pub mod store;
@@ -220,6 +222,9 @@ pub struct Session {
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
/// that starts them ([`Session::load_plugins_in_background`]).
plugin_loads_in_background: bool,
/// The Language packs' generation the documents were last laid out for
/// ([`Session::poll_language_packs`]).
packs_seen: u64,
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
@@ -507,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;
Loaded 100 of 414 files, more files were not shown because too many files have changed in this diff. Show more