Merge main into fix/menu-dialog-kind-names

This commit is contained in:
dotCooCoo committed 2026-11-30 07:26:33 -08:00
commit 42165401b3
258 files changed
+12521 -2512

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()
+6 -5
View File
@@ -39,11 +39,12 @@ 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
+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
+191 -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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# `.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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
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
View File
@@ -163,6 +163,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.
+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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", 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 }
+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)");
}
}
+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"]));
}
}
+83 -46
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.
@@ -384,58 +421,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 +479,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 +546,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 +598,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
@@ -787,9 +818,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 +839,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 +847,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 +873,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.
+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));
+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
@@ -947,3 +947,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);
}
+4
View File
@@ -89,6 +89,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.
+5
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;
@@ -382,6 +384,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());
+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
+2 -2
View File
@@ -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
),
+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")),
}
+9 -2
View File
@@ -162,7 +162,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 +171,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
),
@@ -1163,6 +1163,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() }))
+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 {
+25 -5
View File
@@ -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))
+3 -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,
@@ -226,15 +226,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 +415,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() {
+54 -2
View File
@@ -192,7 +192,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<(NodeId, 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,6 +233,10 @@ 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| Some((*id, node_arc(d, paths.get(id)?)?))).collect();
}
if objects {
for id in &targets {
super::pixelgrid::keep_compound_aligned(d, *id, sc);
@@ -248,7 +256,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 +277,47 @@ 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`). `None` unless every moved object is still that
/// node, none is a member of a blend (whose spine follows its members), and every object the
/// selection shows, the key object and the key anchor's object included, is a moved object or
/// inside one. A pass after the transform that changes a moved object, such as the one that snaps
/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it
/// first, so it is no longer that node.
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(NodeId, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
let d = &st.doc;
let unchanged = |(id, n): &(NodeId, Arc<Node>)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
if held.is_empty() || !held.iter().all(unchanged) {
return None;
}
let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. }));
if held.iter().any(|(id, _)| in_blend(*id)) {
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
+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}))
}
+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",
@@ -104,6 +106,7 @@ pub(super) const ALLOWED: &[&str] = &[
"appearance.removeItem",
"appearance.setActiveItem",
"appearance.setItem",
"appearance.setNewArt",
"appearance.showAllHidden",
"appearance.targetContents",
"appearance.transfer",
+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() {
+6 -2
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"),
+19
View File
@@ -203,6 +203,24 @@ 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 last move of the selected objects that changed nothing else they show ([`Moved`]).
/// Not saved.
pub moved: Option<Moved>,
}
/// 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:
@@ -522,6 +540,7 @@ impl DocState {
measured_in_own: None,
inline_resolved: None,
selection_record: None,
moved: None,
}
}
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
+10
View File
@@ -10,6 +10,9 @@ pub struct Interaction {
pub doc: Arc<Document>,
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
/// 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 +55,13 @@ 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
}
}
/// 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;
+389
View File
@@ -0,0 +1,389 @@
//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence
//! texts of a language other than English, published by storytold/craft-i18n and installed into the
//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where
//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used
//! here too, since the apps share the store.
//!
//! The store downloads only while its download setting is on, which only the person using an app
//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as
//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person
//! allowed downloads.
//!
//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of
//! installs running and one error per locale. In the desktop app installs run on a thread of their
//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents
//! again when one ends; elsewhere they return once installed.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
pub use craft_font_store::Cancel;
/// One pack the pack index lists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pack {
/// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name.
pub locale: String,
/// The language's own name (`Nederlands`).
pub name: String,
/// The download's size in bytes.
pub size: u64,
/// SPDX licence expression of the pack's data.
pub licence: String,
/// The licence class: `Embeddable` or `Download-only`.
pub class: String,
/// Whether it has a spelling dictionary.
pub spelling: bool,
/// Whether it has hyphenation patterns.
pub hyphenation: bool,
}
/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests.
pub trait Backend: Send + Sync {
/// The installed-packs folder craft-proof reads.
fn packs_dir(&self) -> PathBuf;
/// Whether the person allowed downloads.
fn downloads_on(&self) -> bool;
/// The packs of the index fetched last, with no request; empty before the first fetch.
fn cached_index(&self) -> Vec<Pack>;
/// Fetches the pinned pack index (needs downloads on).
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String>;
/// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads
/// on), calling `progress(done, total)` in bytes.
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>;
/// Removes the installed pack for `locale`.
fn remove(&self, locale: &str) -> Result<(), String>;
/// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any.
fn index_override(&self) -> Option<String> {
None
}
}
/// An install running.
struct Job {
done: u64,
total: u64,
cancel: Cancel,
}
#[derive(Default)]
struct Jobs {
installing: BTreeMap<String, Job>,
/// A fetch of the index running.
refreshing: Option<Cancel>,
/// The last failure of each locale's install or removal, and of the index fetch (key `""`).
errors: BTreeMap<String, String>,
}
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() });
static BACKGROUND: AtomicBool = AtomicBool::new(false);
/// Goes up each time the installed packs change.
static GENERATION: AtomicU64 = AtomicU64::new(0);
fn jobs() -> MutexGuard<'static, Jobs> {
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs.
pub fn set_backend(backend: Option<Arc<dyn Backend>>) {
let dir = backend.as_ref().map(|b| b.packs_dir());
*BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend;
craft_proof::packs::set_packs_dir(dir);
changed();
}
/// The backend [`set_backend`] set.
pub fn backend() -> Option<Arc<dyn Backend>> {
BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads
/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there
/// are no packs.
pub fn use_font_store() {
let env = craft_font_catalog::FontEnv::from_process();
set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc<dyn Backend>));
}
/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps
/// working) instead of returning once they are done.
pub fn run_in_background(on: bool) {
BACKGROUND.store(on, Ordering::Relaxed);
}
/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]).
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// Read the packs folder again: spelling and hyphenation in its languages change.
fn changed() {
craft_proof::packs::reload();
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// Whether an install or an index fetch is running.
pub fn busy() -> bool {
let j = jobs();
!j.installing.is_empty() || j.refreshing.is_some()
}
/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language
/// tag of letters and digits, at most 35 bytes, in parts of at most 8.
pub fn parse_locale(raw: &str) -> Result<String, String> {
let l = raw.trim().to_ascii_lowercase().replace('_', "-");
let ok = !l.is_empty()
&& l.len() <= 35
&& l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::<String>())) }
}
fn no_backend() -> String {
"Language packs aren't available: there is no font store folder for this user".into()
}
fn downloads_off() -> String {
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
}
/// The packs the index fetched last lists.
pub fn available() -> Vec<Pack> {
backend().map(|b| b.cached_index()).unwrap_or_default()
}
/// What `proof.packs` reports about the jobs.
pub struct Status {
/// The installs running, as (locale, bytes done, bytes in all).
pub installing: Vec<(String, u64, u64)>,
/// Whether the index is being fetched.
pub refreshing: bool,
/// The last error of each locale (`""`: the index fetch).
pub errors: BTreeMap<String, String>,
}
/// The jobs running and the last errors.
pub fn status() -> Status {
let j = jobs();
Status {
installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(),
refreshing: j.refreshing.is_some(),
errors: j.errors.clone(),
}
}
/// What an install or a fetch did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
/// Done.
Done,
/// Running in the background ([`run_in_background`]).
Started,
}
/// Runs `job` on a thread of its own in the background, else here and gives its own result (never
/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its
/// thread can't start.
fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result<Outcome, String> {
if !BACKGROUND.load(Ordering::Relaxed) {
return job().map(|()| Outcome::Done);
}
match std::thread::Builder::new().name("language-pack".into()).spawn(move || {
// The result is kept in the shared errors for `proof.packs`.
let _ = job();
}) {
Ok(_) => Ok(Outcome::Started),
Err(e) => {
undo();
Err(format!("couldn't start the download: {e}"))
}
}
}
/// Fetches the pinned pack index again. Needs downloads on.
pub fn refresh() -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let cancel = {
let mut j = jobs();
if j.refreshing.is_some() {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.refreshing = Some(cancel.clone());
j.errors.remove("");
cancel
};
run(
move || {
let r = b.fetch_index(&cancel).map(|_| ());
let mut j = jobs();
j.refreshing = None;
if let Err(e) = &r {
j.errors.insert(String::new(), e.clone());
}
r
},
|| jobs().refreshing = None,
)
}
/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs
/// downloads on. Spelling and hyphenation in that language use it once it is installed.
pub fn install(locale: &str) -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let locale = locale.to_string();
let cancel = {
let mut j = jobs();
if j.installing.contains_key(&locale) {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() });
j.errors.remove(&locale);
cancel
};
let l = locale.clone();
run(
move || {
let r = install_now(&*b, &l, &cancel);
// craft-proof reads the new pack before the job ends, so a caller that sees no
// install running sees the pack installed (`proof.packs`, `busy`).
if r.is_ok() {
changed();
}
let mut j = jobs();
j.installing.remove(&l);
if let Err(e) = &r {
j.errors.insert(l, e.clone());
}
r
},
|| {
jobs().installing.remove(&locale);
},
)
}
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
return Err(format!("there is no Language pack for {locale}"));
}
b.install(locale, cancel, &mut |done, total| {
if let Some(job) = jobs().installing.get_mut(locale) {
(job.done, job.total) = (done, total);
}
})
}
/// Stops the install of `locale` (or the index fetch, for `""`) if one is running.
pub fn cancel(locale: &str) {
let j = jobs();
let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) };
if let Some(c) = c {
c.cancel();
}
}
/// Removes the installed pack for `locale`; not while it is installing.
pub fn remove(locale: &str) -> Result<(), String> {
let b = backend().ok_or_else(no_backend)?;
if jobs().installing.contains_key(locale) {
return Err(format!("the {locale} pack is still installing"));
}
let r = b.remove(locale);
changed();
let mut j = jobs();
match &r {
Ok(()) => j.errors.remove(locale),
Err(e) => j.errors.insert(locale.to_string(), e.clone()),
};
r
}
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
/// packs), pinned by the sha256 of its `index.json`. The font store reads
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin {
url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json",
sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b",
};
/// The font store as the packs [`Backend`].
struct FontStoreBackend {
store: craft_font_store::FontStore,
/// The index read or fetched last: an install takes its entry (URL, size, sha256) from it.
index: Mutex<Option<craft_font_store::PackIndex>>,
}
impl FontStoreBackend {
fn new(store: craft_font_store::FontStore) -> Self {
Self { store, index: Mutex::new(None) }
}
fn keep(&self, index: craft_font_store::PackIndex) -> Vec<Pack> {
let packs = index
.packs
.iter()
.map(|e| Pack {
locale: e.locale.clone(),
name: e.name.clone(),
size: e.size,
licence: e.licence.clone(),
class: e.class.clone(),
spelling: e.spelling,
hyphenation: e.hyphenation,
})
.collect();
*self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index);
packs
}
}
impl Backend for FontStoreBackend {
fn packs_dir(&self) -> PathBuf {
self.store.language_packs_dir()
}
fn downloads_on(&self) -> bool {
self.store.network() == craft_font_store::Network::On
}
fn cached_index(&self) -> Vec<Pack> {
self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default()
}
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String> {
let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?;
Ok(self.keep(index))
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone();
let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?;
let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone();
self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string())
}
fn remove(&self, locale: &str) -> Result<(), String> {
self.store.remove_language_pack(locale).map_err(|e| e.to_string())
}
fn index_override(&self) -> Option<String> {
craft_font_store::language_pack_index_overridden()
}
}
/// The font store backend in `dir`, for tests that need the real store without a request.
#[cfg(test)]
pub(crate) fn font_store_in(dir: PathBuf) -> Arc<dyn Backend> {
Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent)))
}
+174 -27
View File
@@ -111,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
variables::after_command(h, before);
}
mod colors;
mod defaults;
mod paths;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -161,14 +168,38 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
/// open, the settings of each `DocumentPreset` the run made, with the size of the values they hold
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
/// gave out.
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
/// written yet, how many times each path's points went stale and each path as the run last saw its
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Vec<ItemList>>,
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
paths: RefCell<Vec<ItemList>>,
/// A path and its subpaths with the point changes the run has made to it and not written yet
/// ([`flush`]).
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
/// The index of the first point of each subpath of the path whose points the run read last,
/// and what they were counted from ([`paths`]).
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
/// How many times the points the run read of each path went stale, by document uid and path id
/// ([`paths`]).
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
/// Each path whose points the run read, as the run last saw it, by document uid and then path
/// id ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
/// The path whose points the object model is writing with `path.setAnchors`, the only path
/// that command changes ([`paths`]).
one_path: Cell<Option<Item>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
/// change.
editing: Cell<Option<Item>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
text: text::TextState,
@@ -223,6 +254,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
const KEPT_LISTS: usize = 8;
/// The list kept in `lists` for the document `st`, while that document is unchanged.
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
}
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
let mut l = lists.borrow_mut();
l.retain(|(uid, ..)| *uid != st.uid);
if l.len() >= KEPT_LISTS {
l.remove(0);
}
l.push((st.uid, st.doc.clone(), ids.clone()));
}
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
@@ -279,15 +328,40 @@ type Answer = std::result::Result<Data, HostError>;
/// A member function: the run's host and the call's arguments, `this` first.
type Member = fn(&Host, &[Data]) -> Answer;
/// A member function that first writes the point changes waiting in [`State`] ([`flush`]).
fn function(link: &Link, f: Member) -> HostFunction {
call(link, f, true)
}
/// A member function of the points of a path, which reads and adds to the point changes waiting in
/// [`State`] instead of writing them first.
fn point_function(link: &Link, f: Member) -> HostFunction {
call(link, f, false)
}
fn call(link: &Link, f: Member, flushing: bool) -> HostFunction {
let l = link.clone();
Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16 + a.iter().map(data_size).sum::<u64>())?;
if flushing {
flush(&h)?;
}
f(&h, &a)
})
}
/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]).
pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
paths::flush(h)
}
/// Notes the changes a command made to the points of the paths the run has read
/// ([`paths::see_all_points`]).
pub(super) fn see_points(h: &Host) {
paths::see_all_points(h)
}
fn get(link: &Link, f: Member) -> HostMember {
HostMember::Get(function(link, f))
}
@@ -300,6 +374,19 @@ fn method(link: &Link, f: Member) -> HostMember {
HostMember::Method(function(link, f))
}
/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]).
fn point_get(link: &Link, f: Member) -> HostMember {
HostMember::Get(point_function(link, f))
}
fn point_property(link: &Link, g: Member, s: Member) -> HostMember {
HostMember::Property { get: point_function(link, g), set: point_function(link, s) }
}
fn point_method(link: &Link, f: Member) -> HostMember {
HostMember::Method(point_function(link, f))
}
/// A member of a class with what `reflect` tells of it.
pub(super) type Described = (String, HostMember, MemberInfo);
@@ -315,8 +402,9 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
/// the check that a document, page item, path point or text range `this` is still there.
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
/// `reflect` leaves it out.
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
@@ -327,9 +415,12 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"Document" => {
doc_of(&h, arg(&a, 0), "Document")?;
}
"PageItem" | "TextFrame" => {
"PageItem" | "PathItem" | "TextFrame" => {
item_of(&h, arg(&a, 0))?;
}
"PathPoint" => {
paths::this_point(&h, &a)?;
}
"TextRange" => {
text::check_range(&h, arg(&a, 0))?;
}
@@ -656,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
return Ok(());
}
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
// Anchors and segments the change removed (a path opened or given fewer points) are left out.
let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| {
doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test))
};
let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len());
let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true));
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
if kept.is_empty() {
command(h, "select.none", &json!({}))?;
@@ -668,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
.iter()
.map(|i| {
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(),
// A path with only segments selected gets them back below, with no anchors.
None if before.segments.contains_key(i) => Vec::new(),
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
@@ -679,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?;
}
for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) {
let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect();
let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect();
if segments.is_empty() {
continue;
}
command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?;
}
let guides: Vec<NodeId> = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect();
@@ -799,9 +899,15 @@ pub(super) fn after_kept_command(h: &Host) {
text::styles::after_command(h);
}
/// Runs `id` with `params` on the item's document, its selection kept.
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
/// paths stay valid through the change ([`paths::see_all_points`]).
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
h.dom.editing.set(kept);
r
}
/// Reads the document of `doc` with `f`.
@@ -1208,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
})
}
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
/// built-in preset with `presetSettings` over them.
const BUILT_IN_SETTINGS: &[&str] = &[
"width",
"height",
"units",
"artboards",
"artboardLayout",
"bleed",
"backgroundContents",
"colorMode",
"rasterEffectsPpi",
"previewMode",
"alignNewObjectsToPixelGrid",
];
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
/// place of the profile's.
@@ -1254,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
}
// The document starts from the first preset of the profile's category (Print: Letter).
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
if let Some(m) = mode {
p.entry("colorMode").or_insert_with(|| json!(m));
}
// The document starts from the first built-in preset of the profile's category (Print:
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
// does not stand in for it. Settings the built-in preset refuses are an error.
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
if let Value::Object(settings) = full.to_json() {
for key in BUILT_IN_SETTINGS {
if let Some(v) = settings.get(*key) {
p.insert((*key).into(), v.clone());
}
}
}
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
// A profile whose file could not be read throws, and the document `file.new` made with the
// defaults is put back, with the Recent sizes as they were.
atomically(h, |h| {
@@ -2008,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let name = &text_arg(arg(a, 1), "name")?;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
@@ -2026,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
/// or a Boolean becomes the text `String(value)` gives.
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let note = &text_arg(arg(a, 1), "note")?;
if note.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the note is too long".into()));
}
let item = this_item(h, a)?;
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
if !same {
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
@@ -2064,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -2074,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let locked = boolean(arg(a, 1), "locked")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -2084,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let v = number(arg(a, 1), "opacity")?;
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
@@ -2093,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
// replaces the one the graph keeps for its series or kind.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let item = this_item(h, a)?;
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
@@ -2139,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
/// would still replace the blend mode a graph keeps for the item's series or kind.
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let mode = match arg(a, 1) {
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
_ => None,
};
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
let item = this_item(h, a)?;
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
@@ -2271,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
}
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let p = point(arg(a, 1), "position")?;
move_to(h, a, Some(p[0]), Some(p[1]))
}
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let x = coordinate(arg(a, 1), "left")?;
move_to(h, a, Some(x), None)
}
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let y = coordinate(arg(a, 1), "top")?;
move_to(h, a, None, Some(y))
}
@@ -2289,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
/// objects included.
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
let item = this_item(h, a)?;
let what = if width { "width" } else { "height" };
let size = number(arg(a, 1), what)?;
if size <= 0.0 || size > MAX_SIZE {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
@@ -2681,6 +2819,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
realm.define_host_object("BlendModes", blend_modes)?;
variables::define_enums(realm)?;
paths::install_enums(realm)?;
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
let l = link;
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
@@ -2778,17 +2917,17 @@ fn classes(link: &Link) -> Vec<HostClass> {
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
),
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }),
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
("toString", method(l, doc_to_string), returns("string", &[])),
]);
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
.into_iter()
.map(|m| later(l, "Document", m)),
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
);
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
@@ -2889,7 +3028,15 @@ fn classes(link: &Link) -> Vec<HostClass> {
);
page_item.extend(variables::page_item_members(l));
classes.push(class("PageItem", None, page_item, None));
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
let mut members = variables::item_members(l, c);
if *c == "PathItem" {
members.extend(paths::path_item_members(l));
}
class(c, Some("PageItem"), members, None)
}));
classes.extend(paths::classes(l));
classes.extend(colors::classes(l));
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.push(class(
+189
View File
@@ -0,0 +1,189 @@
//! The color classes of the script object model, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RGBColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/LabColor/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/> describe them.
//!
//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components,
//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time.
//! Components are checked when a color is assigned to an object, and a value out of range throws a
//! `RangeError` with nothing changed.
//!
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
//! assigned yet.
use std::rc::Rc;
use serde_json::Value;
use vectorcraft_color::{Color, Paint};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
use super::{Link, current, num, text};
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
/// The components of each color class, with the value `new` gives them.
const CLASSES: &[(&str, &[&str])] = &[
("RGBColor", &["red", "green", "blue"]),
("CMYKColor", &["cyan", "magenta", "yellow", "black"]),
("GrayColor", &["gray"]),
("LabColor", &["l", "a", "b"]),
("NoColor", &[]),
("GradientColor", &[]),
("SpotColor", &["tint"]),
("PatternColor", &[]),
];
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
let mut items = vec![("typename".to_string(), text(class))];
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
Data::Object(items)
}
/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that
/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read
/// from an object gives that object the same color.
fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 {
let mut scale = 1e4;
for _ in 4..=9 {
let r = (exact * scale).round() / scale;
if back(r) == v {
return r;
}
scale *= 10.0;
}
exact
}
/// A component stored as `v`, from 0 to 1, that the script sees times `scale`.
fn shown(v: f32, scale: f64) -> f64 {
shown_as(f64::from(v) * scale, v, |r| unit(r, scale))
}
/// The color object for a solid color.
fn of_color(c: &Color) -> Data {
match *c {
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
Color::Cmyk { c, m, y, k } => color_object(
"CMYKColor",
&[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))],
),
Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]),
Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]),
}
}
/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor`
/// with its `tint` for a color linked to a global or spot swatch.
pub(super) fn of_paint(paint: &Paint) -> Data {
match paint {
Paint::None => color_object("NoColor", &[]),
Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]),
Paint::Solid { color, .. } => of_color(color),
Paint::Gradient(_) => color_object("GradientColor", &[]),
Paint::Pattern { .. } => color_object("PatternColor", &[]),
}
}
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
/// stand for an ink amount that no Gray value names exactly).
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
match (assigned, now) {
(None, Paint::None) => true,
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
_ => false,
}
}
/// Whether the color object `d` has the class and every component of `shown`.
fn shows(d: &Data, shown: &Data) -> bool {
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
}
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
None | Some(Data::Undefined) => Ok(0.0),
Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n),
Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))),
Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))),
}
}
#[allow(clippy::cast_possible_truncation)]
fn unit(v: f64, scale: f64) -> f32 {
(v / scale) as f32
}
/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property.
pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color>, HostError> {
let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) };
let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) {
Some(Data::String(s)) => s.as_str(),
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
};
let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max);
Ok(Some(match class {
"NoColor" => return Ok(None),
"RGBColor" => {
Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) }
}
"CMYKColor" => Color::Cmyk {
c: unit(c("cyan", 0.0, 100.0)?, 100.0),
m: unit(c("magenta", 0.0, 100.0)?, 100.0),
y: unit(c("yellow", 0.0, 100.0)?, 100.0),
k: unit(c("black", 0.0, 100.0)?, 100.0),
},
"GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) },
"LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) },
l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))),
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
}))
}
/// `color` as `paint.setFill` and `paint.setStroke` take it.
pub(super) fn param(color: &Color) -> Value {
serde_json::to_value(color).unwrap_or(Value::Null)
}
/// The constructors of the color classes, and `cmykColor`.
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
let make = |name: &str, components: &'static [&'static str]| {
let l = link.clone();
let class = name.to_string();
let f: HostFunction = Rc::new(move |_| {
current(&l)?.charge_call(64)?;
let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect();
Ok(color_object(&class, &zeros))
});
f
};
let mut out: Vec<HostClass> = CLASSES
.iter()
.map(|(name, components)| HostClass {
name: (*name).into(),
parent: None,
members: Vec::new(),
info: Vec::new(),
index: None,
construct: Some(make(name, components)),
})
.collect();
out.push(HostClass {
name: "cmykColor".into(),
parent: None,
members: Vec::new(),
info: Vec::new(),
index: None,
construct: Some(make("CMYKColor", CLASSES[1].1)),
});
out
}
+211
View File
@@ -0,0 +1,211 @@
//! A document's default fill and stroke in the script object model, the `Document` members whose
//! names start with `default` that the help page
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/> describes, and `scaleFactor`.
//!
//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for
//! every open document, as the help page says of these global settings. Reading one reads new
//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the
//! selection, its art, the active proxy and the recent colors as they were. A value that changes
//! nothing runs no command, and a bad value throws an error with nothing changed.
//!
//! VectorCraft's own rules, which the help page does not state:
//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or
//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or
//! `defaultStroked` set to true with no default fill or stroke gives black.
//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores
//! it.
//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of
//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a
//! dash pattern unless it is 0.
//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default
//! throws an error, since new art then takes that object's appearance.
//! - `scaleFactor` is 1: VectorCraft draws every document at its own size.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, LineCap, LineJoin};
use vectorcraft_js::{Data, HostError, MemberInfo};
use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths};
use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed};
/// New art's appearance, after the check that the document `this` names is still open.
fn new_art(h: &Host, a: &[Data]) -> std::result::Result<Appearance, HostError> {
this_doc(h, a)?;
Ok(h.session.borrow().new_art())
}
/// Runs `appearance.setNewArt` with `params`, unless `same`.
fn set(h: &Host, same: bool, params: Value) -> Answer {
if !same {
command(h, "appearance.setNewArt", &params)?;
}
Ok(Data::Undefined)
}
fn top_paint(ap: &Appearance, fill: bool) -> Paint {
if fill { ap.fill_paint() } else { ap.stroke_paint() }
}
fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill)))
}
fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
let color = colors::assigned(arg(a, 1), what)?;
let now = top_paint(&new_art(h, a)?, fill);
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
let paint = match color {
Some(c) => json!({"color": colors::param(&c)}),
None => json!({"none": true}),
};
let key = if fill { "fill" } else { "stroke" };
set(h, same, json!({ key: paint }))
}
fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none()))
}
fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?;
let now = !top_paint(&new_art(h, a)?, fill).is_none();
let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) };
let key = if fill { "fill" } else { "stroke" };
set(h, now == on, json!({ key: paint }))
}
fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
let ap = new_art(h, a)?;
Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) }))
}
fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") };
let on = boolean(arg(a, 1), what)?;
let now = default_overprint(h, a, fill)? == Data::Bool(on);
set(h, now, json!({ key: on }))
}
/// New art's top stroke option `f` reads, or `none` when new art has no stroke.
fn stroke_option<T>(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result<T, HostError> {
Ok(new_art(h, a)?.stroke().map_or(none, f))
}
fn default_stroke_width(h: &Host, a: &[Data]) -> Answer {
this_doc(h, a)?;
Ok(num(h.session.borrow().paint.stroke_width))
}
fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
let w = number(arg(a, 1), "defaultStrokeWidth")?;
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into()));
}
this_doc(h, a)?;
let now = h.session.borrow().paint.stroke_width;
set(h, now == w, json!({"weight": w}))
}
fn default_cap(h: &Host, a: &[Data]) -> Answer {
let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
}
fn set_default_cap(h: &Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
_ => None,
};
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("defaultStrokeCap must be a StrokeCap value".into())) };
let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
set(h, now == cap, json!({"cap": name}))
}
fn default_join(h: &Host, a: &[Data]) -> Answer {
let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
}
fn set_default_join(h: &Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
_ => None,
};
let Some(&(join, _, name)) = found else { return Err(HostError::Type("defaultStrokeJoin must be a StrokeJoin value".into())) };
let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
set(h, now == join, json!({"join": name}))
}
fn default_miter(h: &Host, a: &[Data]) -> Answer {
Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?))
}
fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "defaultStrokeMiterLimit")?;
if !(1.0..=500.0).contains(&v) {
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
}
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
set(h, now == v, json!({"miterLimit": v}))
}
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone()))
}
fn default_dashes(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect()))
}
fn set_default_dashes(h: &Host, a: &[Data]) -> Answer {
let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?;
let now = dashes(h, a)?;
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
set(h, now == lengths, json!({"dash": dash}))
}
fn default_dash_offset(h: &Host, a: &[Data]) -> Answer {
Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?))
}
fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "defaultStrokeDashOffset")?;
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into()));
}
if dashes(h, a)?.is_empty() && v != 0.0 {
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
}
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
set(h, now == v, json!({"dashOffset": v}))
}
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
this_doc(h, a)?;
Ok(num(1.0))
}
/// The `Document` members of this module.
pub(super) fn document_members(l: &Link) -> Vec<Described> {
named(vec![
("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")),
("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")),
("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")),
("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")),
("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")),
("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")),
(
"defaultStrokeWidth",
property(l, default_stroke_width, set_default_stroke_width),
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
),
("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")),
("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")),
("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")),
("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")),
("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")),
("scaleFactor", get(l, scale_factor), typed("number")),
])
}
File diff suppressed because it is too large. Load diff
+88 -18
View File
@@ -163,6 +163,7 @@ pub fn refused_to_scripts(id: &str) -> bool {
"edit.undoGroup.",
"file.recovery.",
"stroke.widthProfile.",
"proof.",
];
const IDS: &[&str] = &[
"text.addFontFiles",
@@ -1174,6 +1175,8 @@ struct Job {
name: String,
/// The file-access scope `script.run` came in, which every slice runs in.
scope: crate::file_access::ScopeHandle,
/// The script has ended, and the run waits for the person's growth answer before it is kept.
finished: bool,
}
/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in
@@ -1402,6 +1405,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
// Point changes that wait in the object model are written before any command runs.
dom::flush(host)?;
let session = host.session.clone();
let started = clock();
let before = dom::before_command(host, id);
@@ -1446,6 +1451,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
dom::after_kept_command(host);
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
@@ -1517,6 +1523,7 @@ pub(crate) fn retained_style_lists(s: &Session) -> usize {
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
/// of a crossing throws a `RangeError`.
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
dom::flush(host)?;
let s = host.session.borrow();
let Some(st) = s.active() else { return Ok(Data::Null) };
let ids: Vec<u64> = st.selection.objects.iter().take(1_000).map(|i| i.0).collect();
@@ -2103,7 +2110,7 @@ impl Session {
if h.waiting.replace(false) {
h.continues.set(h.continues.get() + 1);
h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects()));
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES));
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes()));
}
});
}
@@ -2282,7 +2289,7 @@ impl Session {
bytes_kept: Cell::new(0),
bridge: Cell::new(0),
allowance_objects: Cell::new(growth_objects()),
allowance_bytes: Cell::new(GROWTH_BYTES),
allowance_bytes: Cell::new(growth_bytes()),
continues: Cell::new(0),
waiting: Cell::new(false),
log: RefCell::new(Vec::new()),
@@ -2407,7 +2414,7 @@ impl Session {
}
let scope = crate::file_access::ScopeHandle::capture();
let (run, line_name) = (host.run, host.name.clone());
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope };
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false };
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
self.script_key = Some(JobKey { id, run, name: line_name });
@@ -2461,6 +2468,28 @@ impl Session {
self.script_key = Some(key);
return None;
}
// A run whose script ended past its growth allowance is kept once the person lets it go on,
// and put back when they stop it.
if job.finished {
if self.script_stop.is_set() {
let kind = LimitKind::Interrupted;
let e =
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
// One more allowance may still leave the growth past it: the person is asked again
// while they may be, and past that the run ends unkept.
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
if job.host.waiting.get() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
return None;
}
return Some(self.script_ended(job));
}
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
if job.realm.waits() {
let kind = LimitKind::Interrupted;
@@ -2486,24 +2515,35 @@ impl Session {
self.script_key = Some(key);
None
}
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
let n = job.host.dialogs.unused();
let kind = LimitKind::Host;
let message = if n == 1 {
format!("`answers` has {n} answer the script did not use")
} else {
format!("`answers` has {n} answers the script did not use")
};
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
}
Ok(Ok(Progress::Done(_))) => {
let r = self.script_commit(job);
self.trim_histories();
Some(r)
// The point changes written as the script ended went past the growth allowance.
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
job.finished = true;
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
None
}
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
}
}
/// Ends the run whose script has ended: it fails when answers it was given went unused, and is
/// kept otherwise.
fn script_ended(&mut self, job: Job) -> Result<Value> {
let n = job.host.dialogs.unused();
if n > 0 {
let kind = LimitKind::Host;
let message = if n == 1 {
format!("`answers` has {n} answer the script did not use")
} else {
format!("`answers` has {n} answers the script did not use")
};
return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false });
}
let r = self.script_commit(job);
self.trim_histories();
r
}
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
job.host.dialogs.stopped();
job.host.disk.borrow_mut().picker = None;
@@ -2823,6 +2863,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
std::mem::swap(s, &mut *cell.borrow_mut());
let scope = job.scope.clone();
let realm = &mut job.realm;
let host = &job.host;
let started = clock();
let r = scope.run(|| {
guard::catch_panic(|| {
@@ -2830,7 +2871,14 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
if PANIC_IN_SLICE.with(Cell::get) {
panic!("a slice failed");
}
realm.advance(SLICE_FUEL)
// Point changes that still wait in the object model are written when the script ends. Between
// slices the run's documents are put aside, so they can wait across slices.
realm.advance(SLICE_FUEL).and_then(|progress| {
if matches!(progress, Progress::Done(_)) {
dom::flush(host).map_err(end_flush_error)?;
}
Ok(progress)
})
})
});
if let Some(started) = started {
@@ -2844,6 +2892,17 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
r
}
/// The error that ends a run when the point changes waiting at the end of its script cannot be
/// written.
fn end_flush_error(e: HostError) -> RunError {
let message = match e {
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m,
HostError::Marked { error, .. } => return end_flush_error(*error),
HostError::Wait => "a host function waited for its result where the run cannot pause".into(),
};
RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }
}
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
/// job was removed.
#[cfg(test)]
@@ -2860,6 +2919,15 @@ fn growth_objects() -> u64 {
GROWTH_OBJECTS
}
/// The bytes of new document data a run may keep before it is asked to continue or stop.
fn growth_bytes() -> u64 {
#[cfg(test)]
if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) {
return n;
}
GROWTH_BYTES
}
/// The data a run may pass to and from commands.
fn bridge_bytes() -> u64 {
#[cfg(test)]
@@ -2886,6 +2954,8 @@ thread_local! {
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
+2 -1
View File
@@ -111,6 +111,7 @@ impl Session {
plugin_dir: None,
plugin_loads: Default::default(),
plugin_loads_in_background: false,
packs_seen: 0,
scripts_dir: None,
startup_scripts_dir: None,
script_listing_clock: Default::default(),
@@ -359,7 +360,7 @@ impl Session {
/// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved
/// document stays saved, and its undo history keeps its documents as they are. The document is
/// left as it is when `stale` picks nothing.
fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
let Some(st) = self.docs.get_mut(index) else { return };
if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) {
return;
+1
View File
@@ -545,6 +545,7 @@ impl Session {
effect: None,
doc: st.doc.clone(),
selection: Arc::new(st.selection.clone()),
revision: st.revision,
preview: None,
tool: false,
paint,
+38
View File
@@ -1093,6 +1093,44 @@ impl Session {
self.plugin_loads_in_background = on;
}
/// Lays every document out again when the installed Language packs changed since the last
/// call (an install in the background ended, or a pack was removed), since spelling and
/// hyphenation in their languages change → whether an install or index fetch is still running,
/// so the app looks again. The app calls it as its frames go by.
pub fn poll_language_packs(&mut self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
// Busy first: an install moves the generation on before it ends, so when none is
// running any more its change is read below.
let busy = crate::packs::busy();
let now = crate::packs::generation();
if now != self.packs_seen {
self.packs_seen = now;
for index in 0..self.docs.len() {
// A document in the back is measured in its own composite fonts, lent for the
// measuring, as `measure_back_document` does: the front document's are the
// ones registered, and one of the same name may differ.
let back_fonts = (self.active != Some(index)).then(|| self.docs.get(index).map(|st| st.doc.composite_fonts.clone())).flatten();
let lent = back_fonts.as_ref().map(|fonts| vectorcraft_text::FontDb::global().lend_document_composite_fonts(fonts));
// Type in a language of its own may break its lines elsewhere now: it is
// measured again (not an edit), so its selection box and hits follow.
self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some()));
drop(lent);
if let Some(st) = self.docs.get_mut(index) {
st.revision += 1;
}
}
}
busy
}
// The web build has no packs.
#[cfg(target_arch = "wasm32")]
{
let _ = self.packs_seen;
false
}
}
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
/// load's file-name order, up to the first module still loading, without waiting → whether
/// some are still loading. A load starts once the loads before it are done. When another
+5
View File
@@ -118,6 +118,7 @@ mod livecorners;
mod maskview;
pub(super) mod menucmds;
mod mesh_picks;
mod moved;
mod nativefile;
mod newart;
mod newdoc;
@@ -128,6 +129,8 @@ mod outlineobject;
pub(super) mod outlinestroke;
mod overprint;
mod package;
#[cfg(not(target_arch = "wasm32"))]
mod packs;
mod paintopacity;
mod paintproxy;
mod panelcmds;
@@ -180,6 +183,8 @@ mod script_console;
mod script_dialogs;
mod script_dollar;
mod script_dom;
mod script_dom_defaults;
mod script_dom_paths;
mod script_engines;
mod script_folder;
mod script_include;
+55
View File
@@ -3048,6 +3048,61 @@ fn symbol_export_type_defaults_to_movie_clip_and_round_trips() {
assert!(s.execute("symbol.options", &json!({"name": "Renamed"})).is_err());
}
/// `symbol.options` whose values are the ones the symbol already has changes neither the document
/// nor its revision, and records no undo step.
#[test]
fn symbol_options_that_change_nothing_record_no_undo_step() {
let mut s = session();
make_symbol(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let unchanged = [
json!({"name": "Box", "newName": "Box"}),
json!({"name": "Box", "newName": " Box "}),
json!({"name": "Box", "registration": 4}),
json!({"name": "Box", "exportType": "movieClip"}),
json!({"name": "Box", "nineSlice": false}),
json!({"name": "Box", "type": "static"}),
json!({"name": "Box", "alignToPixelGrid": false}),
json!({"name": "Box", "newName": "Box", "registration": 4, "exportType": "movieClip", "type": "static", "alignToPixelGrid": false}),
];
let before = state(&s);
for p in &unchanged {
assert_eq!(s.execute("symbol.options", p).unwrap()["name"], "Box");
assert_eq!(state(&s), before, "{p} changes nothing");
}
s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "changed options are one undo step");
let before = state(&s);
let r = s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
assert_eq!((r["registration"].clone(), r["exportType"].clone(), r["type"].clone()), (json!(0), json!("graphic"), json!("dynamic")));
assert_eq!(state(&s), before, "setting the options again changes nothing");
s.execute("symbol.options", &json!({"name": "Box", "newName": "Logo"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
}
/// `symbol.replace` with the symbol the instances already show changes neither the document nor
/// its revision, and records no undo step.
#[test]
fn symbol_replace_with_the_same_symbol_records_no_undo_step() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "Small"})).unwrap();
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
assert_eq!(s.execute("symbol.replace", &json!({"name": "Box", "ids": [inst.0]})).unwrap()["ids"], json!([inst.0]));
assert_eq!(state(&s), before, "replacing an instance with its own symbol changes nothing");
s.execute("symbol.replace", &json!({"name": "Small", "ids": [inst.0]})).unwrap();
assert!(matches!(&node(&s, inst).kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Small"));
assert_eq!(undo_steps(&s), before.2 + 1, "replacing it with another symbol is one undo step");
}
#[test]
fn sprayer_command_creates_a_symbol_set_and_alt_removes() {
let mut s = session();
@@ -1184,6 +1184,28 @@ fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
}
#[test]
fn transparency_info_reports_the_picked_object_that_transparency_set_edits() {
let mut s = session();
let inst = pair(&mut s, "dynamic");
s.execute("transparency.set", &json!({"ids": [inst.0], "opacity": 75, "blend": "screen", "isolate": true, "knockout": "on"})).unwrap();
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap();
let shown = |v: &Value| (v["ids"].clone(), v["opacity"].as_f64(), v["blend"].clone(), v["isolate"].clone(), v["knockout"].clone());
// Without ids, the picked object's opacity and blend mode, and the instance's isolate and knockout.
let info = s.execute("transparency.info", &json!({})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(50.0), json!("Multiply"), json!(true), json!("on")));
let panel = s.transparency_info();
assert_eq!((panel.opacity, panel.blend.map(vectorcraft_color::BlendMode::label)), (Some(50.0), Some("Multiply")));
// The other object of the art draws as the symbol does.
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [0]})).unwrap();
let info = s.execute("transparency.info", &json!({})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(100.0), json!("Normal"), json!(true), json!("on")));
// With the instance's id, the instance itself, as transparency.set with that id edits it.
let info = s.execute("transparency.info", &json!({"id": inst.0})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(75.0), json!("Screen"), json!(true), json!("on")));
}
#[test]
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
let mut s = session();
+240 -5
View File
@@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged");
sel(&mut s, &[copies[0]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
sel(&mut s, &[copies[1]]);
@@ -150,21 +150,220 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
let moved = node(&s, copies[1]).stroke_path().unwrap();
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
}
#[test]
fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
// The outlines `highlights` gives, and how many objects it looked at for them.
let shown = |s: &Session| {
let before = walked();
let out = highlights(s);
(out, walked() - before)
};
// The outlines in each layer color.
let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::<Vec<_>>();
// The outlines a walk finds, the options set again so that nothing is kept.
let fresh = |s: &mut Session| {
let size = s.global_edit_options.size;
s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap();
highlights(s);
s.execute("select.globalEditOptions", &json!({"size": size})).unwrap();
let before = walked();
let out = highlights(s);
assert!(walked() > before, "a walk");
paths(&out)
};
let mut s = session();
let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3);
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect();
sel(&mut s, &[key]);
let (first, n) = shown(&s);
assert_eq!(first.len(), 39);
assert!(n >= 40, "the first preview walks every object");
// The move rounds the form in its unit box differently; the same objects are like it.
s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap();
let (out, n) = shown(&s);
assert_eq!(n, 0, "a move of the selected object alone compares the others as before");
assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked");
assert_eq!(paths(&out), fresh(&mut s));
// Another object moved: it is shown where it is now.
sel(&mut s, &[copies[0]]);
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
sel(&mut s, &[key]);
let (out, n) = shown(&s);
assert!(n > 0, "another object changed");
let moved = node(&s, copies[0]).stroke_path().unwrap();
assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
assert_eq!(paths(&out), fresh(&mut s));
// The selected object took another shape: none of the squares is like it.
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
// With Size, a larger copy of the selected square is another size.
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
// With Appearance, another fill on the selected square leaves the others out.
s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the others have another fill now");
s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap();
// Reflected, the selected kite keeps its size but is no longer like its copy.
let lone = kite(&mut s, 0.0, 500.0, 1.0);
kite(&mut s, 200.0, 500.0, 1.0);
sel(&mut s, &[lone]);
assert_eq!(shown(&s).0.len(), 1);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "a reflected copy is not like it");
}
#[test]
fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 3);
s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [key]);
assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out");
}
#[test]
fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
rect(&mut s, 1100.0, 100.0, 10.0, 10.0);
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out");
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now");
}
#[test]
fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap();
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert!(highlights(&s).is_empty(), "the other instance is on the canvas");
// The symbol's art drawn 400 pt to the left: the other instance lies on the artboard.
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
let art = std::sync::Arc::make_mut(&mut d.symbols[0].art);
art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default());
st.revision += 1;
assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now");
}
#[test]
fn a_symbol_instance_put_in_perspective_has_another_size() {
use crate::cmd::globaledit::highlights;
let mut s = session();
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1);
let size = |s: &Session| bounds(s, key).size();
let was = size(&s);
s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap();
sel(&mut s, &[key]);
assert_ne!(size(&s), was, "the projection changes the instance's size");
assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had");
}
#[test]
fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap();
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1);
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art");
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1, "the whole instance again");
}
#[test]
fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
let mut s = session();
let group = |s: &mut Session, ids: &[NodeId]| {
sel(s, ids);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
};
// A group of two squares inside an outer group with a third square, and a copy of both: the
// copy's inner group is like the selected inner group.
let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)];
let inner = group(&mut s, &a);
let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let outer = group(&mut s, &[inner, third]);
let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)];
let inner_copy = group(&mut s, &b);
let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0);
group(&mut s, &[inner_copy, third_copy]);
sel(&mut s, &[inner]);
let first = highlights(&s);
assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one");
assert!(!first.is_empty());
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = walked();
assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first));
assert_eq!(walked(), before, "the outer group changed with the selected group only");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same");
assert!(walked() > before);
}
#[test]
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
let mut s = session();
let [a, b, ..] = squares(&mut s);
let outline = node(&s, b).stroke_path().unwrap();
let shown = |s: &mut Session| {
s.overlays(ViewInfo::default())
.iter()
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline)))
};
sel(&mut s, &[a]);
s.select_tool("selection", ViewInfo::default()).unwrap();
@@ -175,6 +374,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
assert!(shown(&mut s), "while Global Edit is on, with any tool");
}
/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the
/// revision changes when the outlines are found again.
#[test]
fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() {
use std::sync::Arc;
use vectorcraft_tools::Overlay;
let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> {
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None })
.collect()
};
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for i in 1..200 {
rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0);
}
sel(&mut s, &[key]);
s.select_tool("selection", ViewInfo::default()).unwrap();
let first = outlines(&mut s);
let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) };
assert_eq!(paths.len(), 199);
let second = outlines(&mut s);
let [(again, same)] = &second[..] else { panic!("{}", second.len()) };
assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy");
assert_eq!(same, revision);
s.execute("select.globalEdit", &json!({})).unwrap();
let on = outlines(&mut s);
let [(members, started)] = &on[..] else { panic!("{}", on.len()) };
assert_eq!(members.len(), 199);
assert_ne!(started, revision, "outlines found again take a new revision");
let next = outlines(&mut s);
let [(kept, still)] = &next[..] else { panic!("{}", next.len()) };
assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on");
}
#[test]
fn size_and_appearance_options_narrow_the_match() {
let mut s = session();
+127
View File
@@ -0,0 +1,127 @@
//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far
//! it went, and only when every object the selection shows is the one before it, moved that far.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_geom::Vec2;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn doc(s: &Session) -> Arc<Document> {
s.doc().unwrap().doc.clone()
}
/// The move [`DocState::moved`] names, when it took `from` to the document now.
fn moved_from(s: &Session, from: &Arc<Document>) -> Option<Vec2> {
let st = s.doc().unwrap();
let m = st.moved.as_ref()?;
(m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by)
}
// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the
// document the drag began with.
#[test]
fn a_move_of_whole_objects_names_the_documents_and_the_distance() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a, b]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap();
assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move");
let before = doc(&s);
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge");
let start = doc(&s);
s.begin_interaction("Move").unwrap();
for dx in [3.0, 7.5] {
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap();
assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}");
}
}
// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move
// of part of what the selection shows name no move.
#[test]
fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a, b]);
let cases = [
("object.move", json!({"dx": 12, "dy": 0, "copy": true})),
("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})),
("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})),
("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})),
("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})),
];
for (cmd, p) in cases {
select(&mut s, &[a, b]);
let before = doc(&s);
s.execute(cmd, &p).unwrap();
assert_eq!(moved_from(&s, &before), None, "{cmd} {p}");
}
}
// The key object is shown too: a move that leaves it where it was names no move.
#[test]
fn a_key_object_left_where_it_was_names_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a]);
s.active_mut().unwrap().selection.key = Some(b);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None);
}
// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel
// grid snaps after the edit: neither is the object before the move moved by its distance.
#[test]
fn objects_that_snap_to_the_pixel_grid_name_no_move() {
let mut s = session();
let a = rect(&mut s, 20.0);
select(&mut s, &[a]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let before = doc(&s);
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path");
let mut s = session();
let art = rect(&mut s, 20.0);
let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap();
select(&mut s, &[id_of(&made)]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid");
}
// A member of a blend moved on its own changes the blend's spine.
#[test]
fn a_member_of_a_blend_names_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0));
s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap();
select(&mut s, &[a]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None);
}
+97
View File
@@ -1,6 +1,8 @@
//! The new-art template (M3.65): Stroke panel options and graphic styles chosen with nothing
//! selected, New Art Has Basic Appearance and `paint.default`.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, Dash, LineCap, Node};
@@ -377,3 +379,98 @@ fn fill_line_gives_a_new_line_the_current_fill() {
assert_ne!(s.paint.fill, Paint::None);
assert!(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "fill": "yes"})).is_err());
}
/// `appearance.setNewArt` sets what the next object gets while the selection keeps its own look.
#[test]
fn set_new_art_changes_the_next_object_and_not_the_selection() {
let mut s = session();
let picked = rect(&mut s, 20.0);
run(&mut s, "select.set", json!({"ids": [picked.0]}));
let (look, undo, recent, active) = (node(&s, picked).appearance, undo_len(&s), s.recent_colors.clone(), s.fill_active);
let r = run(
&mut s,
"appearance.setNewArt",
json!({"fill": {"color": "#ff0000"}, "stroke": {"none": true}, "weight": 4, "cap": "round", "dash": [3, 1], "dashOffset": 1, "fillOverprint": true}),
);
assert_eq!(r, json!({"changed": true}));
assert_eq!(node(&s, picked).appearance, look, "the selected art kept its look");
assert_eq!(s.doc().unwrap().selection.objects, vec![picked]);
assert_eq!((undo_len(&s), &s.recent_colors, s.fill_active), (undo, &recent, active));
run(&mut s, "select.none", json!({}));
let id = rect(&mut s, 200.0);
let ap = node(&s, id).appearance;
let (fill, st) = (ap.fill().unwrap(), ap.stroke().unwrap());
assert_eq!(fill.paint, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
assert!(fill.overprint);
assert_eq!((st.paint.clone(), st.width, st.cap), (Paint::None, 4.0, LineCap::Round));
assert_eq!(st.dash, Some(Dash { pattern: vec![3.0, 1.0], offset: 1.0, ..Default::default() }));
// The same values again change nothing.
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 4, "cap": "round"})), json!({"changed": false}));
}
#[test]
fn set_new_art_refuses_bad_values_with_nothing_changed() {
let mut s = session();
let before = s.paint.clone();
for params in [
json!({"weight": -1}),
json!({"weight": 1001}),
json!({"weight": "3"}),
json!({"miterLimit": 0.5}),
json!({"cap": "flat"}),
json!({"join": 2}),
json!({"dash": [0, 0]}),
json!({"dash": [-1]}),
json!({"dash": "4 2"}),
json!({"dashOffset": 2}),
json!({"fill": "#ff0000"}),
json!({"fill": {}}),
json!({"fill": {"color": "#ff0000"}, "weight": -1}),
json!({"stroke": {"tint": 50, "color": "#000000"}}),
json!({"fillOverprint": "yes"}),
json!({"widht": 3}),
// A setting a paint does not take, here or nested in it, is refused too.
json!({"fill": {"color": "#ff0000", "opacity": 25}}),
json!({"stroke": {"none": true, "weight": 2}}),
] {
assert!(s.execute("appearance.setNewArt", &params).is_err(), "accepted {params}");
assert_eq!(s.paint, before, "changed new art for {params}");
}
}
#[test]
fn set_new_art_refuses_a_tint_on_a_pattern_without_a_swatch_entry() {
let mut s = session();
let id = rect(&mut s, 20.0);
let name = run(&mut s, "object.pattern.make", json!({"ids": [id.0], "edit": false}))["name"].as_str().unwrap().to_string();
run(&mut s, "select.none", json!({}));
Arc::make_mut(&mut s.doc_mut().unwrap().doc).remove_swatch(&name);
let before = s.paint.clone();
assert!(s.execute("appearance.setNewArt", &json!({"fill": {"swatch": name, "tint": 50}})).is_err(), "accepted a tint on {name}");
assert_eq!(s.paint, before);
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"fill": {"swatch": name}})), json!({"changed": true}));
}
#[test]
fn set_new_art_refuses_a_swatch_that_is_not_a_name() {
let mut s = session();
let before = s.paint.clone();
for p in [json!({"fill": {"swatch": 7, "color": "#ff0000"}}), json!({"stroke": {"swatch": null, "color": "#ff0000"}})] {
assert!(s.execute("appearance.setNewArt", &p).is_err(), "accepted {p}");
assert_eq!(s.paint, before, "{p} changed new art");
}
}
#[test]
fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
let mut s = session();
let picked = rect(&mut s, 20.0);
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
run(&mut s, "select.set", json!({"ids": [picked.0]}));
let before = s.paint.clone();
assert!(s.execute("appearance.setNewArt", &json!({"weight": 7})).is_err());
assert_eq!(s.paint, before);
run(&mut s, "select.none", json!({}));
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true}));
assert_eq!(s.new_art().stroke().unwrap().width, 7.0);
}
+10
View File
@@ -161,6 +161,8 @@ fn ppi_overprint_preview_and_bad_params() {
json!({"artboardLayout": {"layout": "spiral"}}),
json!({"artboardLayout": {"columns": 0}}),
json!({"artboardLayout": {"rows": 0}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.4}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1001}}),
json!({"artboardLayout": {"tiles": 2}}),
json!({"units": "furlongs"}),
json!({"width": 160000, "artboards": 1000}),
@@ -1212,3 +1214,11 @@ fn the_new_layer_takes_an_id_no_profile_art_has() {
// Ids given out later skip the symbol's art too.
assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next);
}
#[test]
fn a_saved_presets_rows_are_read_within_the_artboard_limit() {
let rows = |n: u32| serde_json::from_value::<crate::cmd::newdoc::DocSettings>(json!({"rows": n})).unwrap().rows;
assert_eq!(rows(1001), crate::cmd::newdoc::MAX_ARTBOARDS, "file.new takes the listed rows again");
assert_eq!(rows(0), 0, "0 stays: columns in their place");
assert_eq!(rows(12), 12, "more rows than artboards stay");
}
+267
View File
@@ -0,0 +1,267 @@
//! Language packs (`proof.packs`, `proof.installPack`, `proof.removePack`, #4936): an installed pack
//! spell-checks its language in the documents, an install needs downloads on, and a pack installed
//! in the background reaches the documents once it ends.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use serde_json::{Value, json};
use crate::packs::{self, Backend, Cancel, Pack};
use crate::*;
/// Tests that set the process-wide packs backend take turns.
fn packs_lock() -> MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Puts the process back to no packs and no background installs when dropped, also when the test
/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then
/// it deletes the test's folder.
struct Reset(PathBuf);
impl Drop for Reset {
fn drop(&mut self) {
while packs::busy() {
for (locale, _, _) in packs::status().installing {
packs::cancel(&locale);
}
packs::cancel("");
std::thread::yield_now();
}
packs::run_in_background(false);
packs::set_backend(None);
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A new folder for one test.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-packs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// Writes a small Dutch pack into `packs/nl`, laid out as the font store unpacks one.
fn write_dutch_pack(packs: &Path) {
let dir = packs.join("nl");
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
std::fs::write(dir.join("pack.toml"), "locale = \"nl\"\nname = \"Nederlands (test)\"\nlicence = \"MIT\"\n").unwrap();
std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap();
std::fs::write(dir.join("spelling.aff"), "SET UTF-8\nTRY esianrtolducgmphbykfvwjzxq\n").unwrap();
std::fs::write(dir.join("spelling.dic"), "5\nhet\nhuis\nen\nde\nfiets\n").unwrap();
}
/// A session with a new document holding Dutch point type with one misspelt word, `fietz`.
fn dutch_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Het huis en de fietz"})).unwrap()["id"].clone();
s.execute("text.setFormat", &json!({"ids": [id], "language": "Dutch"})).unwrap();
s
}
/// The unknown words a check lists, as (word, lang).
fn unknown(s: &mut Session) -> Vec<(String, String)> {
let r = s.execute("text.spelling.check", &json!({})).unwrap();
r["words"].as_array().unwrap().iter().map(|w| (w["word"].as_str().unwrap().into(), w["lang"].as_str().unwrap().into())).collect()
}
fn installed_locales(s: &mut Session) -> Vec<String> {
let r = s.execute("proof.packs", &json!({})).unwrap();
r["installed"].as_array().unwrap().iter().map(|p| p["locale"].as_str().unwrap().to_string()).collect()
}
#[test]
fn a_pack_in_the_font_store_checks_its_language_until_it_is_removed() {
let _turn = packs_lock();
let root = folder("store");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
// A pack another Craft app installed into the shared store.
let store = packs::font_store_in(root.clone());
write_dutch_pack(&store.packs_dir());
packs::set_backend(Some(store));
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())], "checked in Dutch by the pack");
assert_eq!(installed_locales(&mut s), ["nl"]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!((listed["available"].clone(), listed["downloads"].clone()), (json!(true), json!(false)), "downloads stay off");
let before = s.doc().unwrap().revision;
assert_eq!(s.execute("proof.removePack", &json!({"locale": "NL"})).unwrap()["installed"], false);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), without, "checked as before the pack");
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.removePack", &json!({"locale": "nl"})).is_err(), "no longer installed");
}
/// A stand-in for the font store: it lists a Dutch pack and installs it by writing its files.
struct Fake {
dir: PathBuf,
downloads: bool,
/// While set, an install waits until it is cleared.
hold: AtomicBool,
}
impl Backend for Fake {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
self.downloads
}
fn cached_index(&self) -> Vec<Pack> {
let nl = Pack {
locale: "nl".into(),
name: "Nederlands".into(),
size: 2,
licence: "MIT".into(),
class: "Embeddable".into(),
spelling: true,
hyphenation: false,
};
vec![nl]
}
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
Ok(self.cached_index())
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
progress(1, 2);
while self.hold.load(Ordering::Relaxed) {
if cancel.is_cancelled() {
return Err("cancelled".into());
}
std::thread::yield_now();
}
// The index lists only Dutch, which `packs::install` checks first.
if locale != "nl" {
return Err(format!("asked to install {locale}"));
}
write_dutch_pack(&self.dir);
Ok(())
}
fn remove(&self, locale: &str) -> std::result::Result<(), String> {
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
}
}
fn error(s: &mut Session, id: &str, p: Value) -> String {
s.execute(id, &p).unwrap_err().to_string()
}
#[test]
fn an_install_needs_downloads_on_and_a_pack_the_index_lists() {
let _turn = packs_lock();
let root = folder("fake");
let _reset = Reset(root.clone());
let mut s = dutch_session();
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("aren't available"), "no store, no packs");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: false, hold: AtomicBool::new(false) })));
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("downloading is turned off"));
assert!(error(&mut s, "proof.packs", json!({"refresh": true})).contains("downloading is turned off"));
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
for bad in [json!({}), json!({"locale": ""}), json!({"locale": "../nl"}), json!({"locale": 5})] {
assert!(s.execute("proof.installPack", &bad).is_err(), "{bad} is refused");
}
assert!(!root.exists(), "a refused locale writes nothing");
assert!(error(&mut s, "proof.installPack", json!({"locale": "fy"})).contains("no Language pack for fy"));
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["fy"].is_string(), "the failure is reported");
let before = s.doc().unwrap().revision;
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl_NL"})).contains("no Language pack for nl-nl"), "nl_NL reads as nl-nl");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["packs"][0]["installed"], true);
}
#[test]
fn an_install_in_the_background_reaches_the_documents_when_it_ends() {
let _turn = packs_lock();
let root = folder("background");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
let fake = Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) });
packs::set_backend(Some(fake.clone()));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true, "asked again, it is the same install");
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["installing"][0]["locale"], "nl");
assert!(error(&mut s, "proof.removePack", json!({"locale": "nl"})).contains("still installing"));
assert_eq!(unknown(&mut s), without, "not used before it is installed");
let before = s.doc().unwrap().revision;
fake.hold.store(false, Ordering::Relaxed);
while s.poll_language_packs() {
std::thread::yield_now();
}
s.poll_language_packs();
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
}
#[test]
fn a_cancelled_background_install_installs_nothing() {
let _turn = packs_lock();
let root = folder("cancel");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) })));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
packs::cancel("nl");
while packs::busy() {
std::thread::yield_now();
}
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled"));
}
/// A caller confined to automation roots lists the packs but can't fetch, install or remove them:
/// the store they are written into is outside its roots.
#[test]
fn a_confined_caller_lists_packs_but_cannot_change_them() {
let _turn = packs_lock();
let root = folder("confined");
let _reset = Reset(root.clone());
let roots_dir = folder("confined-roots");
std::fs::create_dir_all(&roots_dir).unwrap();
let mut s = dutch_session();
write_dutch_pack(&root);
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap();
let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string());
for (cmd, p) in
[("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))]
{
let e = confined(cmd, p).unwrap_err();
assert!(e.contains("automation path rejected"), "{cmd}: {e}");
}
assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed");
assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there");
let _ = std::fs::remove_dir_all(&roots_dir);
}
/// A script's rollback cannot put back what an install writes into the shared font store, so a
/// script cannot run the pack commands.
#[test]
fn a_script_cannot_install_a_pack() {
let _turn = packs_lock();
let root = folder("script");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let e = error(&mut s, "script.run", json!({"source": "vc.run('proof.installPack', {locale: 'nl'});", "name": "t.js"}));
assert!(e.contains("a script cannot run `proof.installPack`"), "{e}");
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs");
}
+56
View File
@@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() {
assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back");
}
/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale
/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again
/// after every step of a drag, so a decode there redid a large image's whole decode each step.
#[test]
fn image_color_mode_reads_the_header_without_decoding_the_pixels() {
let raw: Vec<u8> = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect();
let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
assert_eq!(cmd::place::color_mode(&png), "Grayscale");
// Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC.
let mut at = 8;
let mut idat = 0;
while at + 12 <= png.len() {
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
if &png[at + 4..at + 8] == b"IDAT" {
png[at + 8..at + 8 + len].fill(0);
let crc = crc32fast::hash(&png[at + 4..at + 8 + len]);
png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
idat += 1;
}
at += 12 + len;
}
assert!(idat > 0, "the PNG has pixel data");
assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode");
assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode");
}
/// The colour mode read from a file's header is the one its decoded pixels have, in every format
/// and channel layout the codecs write.
#[test]
fn image_color_mode_from_the_header_matches_the_decoded_pixels() {
use craft_image_codecs::{ChannelLayout as L, Format as F};
let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) {
Ok(L::Gray | L::GrayA) => "Grayscale",
Ok(L::Cmyk | L::CmykA) => "CMYK",
Ok(_) => "RGB",
Err(e) => panic!("the written file decodes: {e}"),
};
let mut seen = std::collections::BTreeSet::new();
let mut checked = 0;
for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] {
for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] {
let n = 16 * 16 * layout.channels();
let raw: Vec<u8> = (0..n).map(|i| (i * 13 % 256) as u8).collect();
let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap();
let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue };
let want = decoded(&bytes);
assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}");
seen.insert(want);
checked += 1;
}
}
assert!(checked >= 12, "{checked} files written");
assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CMYK", "Grayscale", "RGB"]);
}
#[test]
fn replace_needs_exactly_one_selected_object() {
let mut s = session();
+28 -20
View File
@@ -2347,29 +2347,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct HeldLoad {
_lock: std::sync::MutexGuard<'static, ()>,
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
go: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl HeldLoad {
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
/// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that
/// runs on the thread that made this one is not held, since nothing could let it go: it goes
/// ahead at once and says so in `gave_up`.
fn new(path: std::path::PathBuf) -> HeldLoad {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
let go = Arc::new((Mutex::new(false), Condvar::new()));
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
let test_thread = std::thread::current().id();
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
if p != path {
return;
}
e.store(true, Ordering::SeqCst);
if !(0..1_000_000).any(|_| {
std::thread::yield_now();
g.load(Ordering::SeqCst)
}) {
if std::thread::current().id() == test_thread {
q.store(true, Ordering::SeqCst);
return;
}
let (open, opened) = &*g;
let mut open = open.lock().unwrap_or_else(|e| e.into_inner());
while !*open {
open = opened.wait(open).unwrap_or_else(|e| e.into_inner());
}
}));
HeldLoad { _lock: lock, entered, go, gave_up }
@@ -2380,7 +2386,9 @@ impl HeldLoad {
}
fn release(&self) {
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
let (open, opened) = &*self.go;
*open.lock().unwrap_or_else(|e| e.into_inner()) = true;
opened.notify_all();
}
fn gave_up(&self) -> bool {
@@ -2904,6 +2912,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
#[test]
fn a_query_runs_while_the_plugins_load() {
let id = "test.engine.background.query";
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
let (folder, path) = store_with("plugin-background-query", id);
let held = HeldLoad::new(path);
let mut s = session();
@@ -2917,7 +2926,6 @@ fn a_query_runs_while_the_plugins_load() {
let waited = held.gave_up() || !s.plugins_loading();
held.release();
assert!(!waited, "document.info waited for the plug-ins to load");
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
s.finish_plugin_loads();
assert!(vectorcraft_plugins::registry::remove(id));
}
@@ -2935,18 +2943,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
while !held.entered() && !held.gave_up() {
std::thread::yield_now();
}
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
// tenth of the yields the held load waits before it gives up).
let free = (0..100_000).any(|_| {
// A load run on this thread isn't held, so a free lock then shows nothing.
assert!(!held.gave_up(), "the module loaded on the test's thread");
// Other tests take the lock for a moment; the held load holding it would hold it until it is let go.
while !crate::cmd::plugin::plugin_changes_free() {
std::thread::yield_now();
crate::cmd::plugin::plugin_changes_free()
});
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
let gave_up = held.gave_up();
}
held.release();
s.finish_plugin_loads();
assert!(!gave_up, "the held load gave up before the lock was looked at");
assert!(free, "the lock was held while the module loaded");
assert!(vectorcraft_plugins::registry::remove(id));
}
@@ -2974,6 +2978,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() {
std::thread::yield_now();
}
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
assert!(s.plugins_loading(), "the second module is still loading");
// Canceling waits for a running load until its deadline; the second module, let go, loads
// while the cancel runs or before it, and doesn't install either way.
held.release();
s.cancel_plugin_loads();
// The file goes once it holds no grant.
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
+67 -5
View File
@@ -1017,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
assert_eq!(plain.grid_columns(), spaced.grid_columns());
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
assert!(e.contains("rows must be 1 or more"), "{e}");
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
for layout in ["gridByRow", "row", "column"] {
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
@@ -1074,6 +1074,22 @@ fn an_edit_keeps_direct_selected_anchors() {
assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore");
}
#[test]
fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() {
let (mut s, a, b) = doc();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
let anchors = s.active().unwrap().selection.anchors.clone();
assert!(anchors.contains_key(&a));
// Lists start with the topmost object, so `b` is `pageItems[0]`.
log(&mut s, "app.activeDocument.pageItems[0].selected = false;");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone()));
log(&mut s, "app.activeDocument.pageItems[0].selected = true;");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a)));
}
#[test]
fn an_edit_keeps_the_order_of_a_mixed_selection() {
let (mut s, a, b) = doc();
@@ -1259,9 +1275,11 @@ fn a_startup_preset_alone_gives_its_first_size() {
#[test]
fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
let (mut s, _, _) = doc();
for source in
["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
{
for source in [
"app.activeDocument.pageItems[0].isIsolated;",
"app.activeDocument.pageItems[0].uuid = 'x';",
"app.activeDocument.pageItems[0].transform(5);",
] {
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
}
assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet"));
@@ -1443,6 +1461,16 @@ fn note_is_the_attributes_note() {
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
}
#[test]
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
let mut s = Session::new();
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
}
#[test]
fn document_preset_applies_only_its_given_fields() {
let mut s = Session::new();
@@ -1477,6 +1505,17 @@ fn document_preset_applies_only_its_given_fields() {
assert!(e.contains(part), "{source}: {e}");
}
assert_eq!(s.documents().len(), 2, "a refused preset makes no document");
// A saved preset with the built-in preset's name does not make the refused settings fit.
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboardLayout": "column"})).unwrap();
// With the layout unset, the built-in preset puts the five 1,000,000 pt artboards in one row,
// which does not fit, while the saved preset would put them in one column.
let e = failure(
&mut s,
"var p = new DocumentPreset(); p.width = 1000000; p.numArtboards = 5;\
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; app.documents.addDocument('Print', p);",
);
assert!(e.contains("don't fit"), "{e}");
assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document");
}
#[test]
@@ -1663,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() {
assert!(e.contains("Stale page item"), "{e}");
}
/// A setter on a removed item reports the stale item before it checks the value it was given.
#[test]
fn setters_on_a_stale_item_report_it_before_a_bad_value() {
let (mut s, _, _) = doc();
for set in [
"name = {}",
"note = {}",
"hidden = 'x'",
"locked = 'x'",
"opacity = 500",
"blendingMode = 'x'",
"selected = 'x'",
"position = 'x'",
"left = 'x'",
"top = 'x'",
"width = -1",
"height = -1",
] {
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};"));
assert!(e.contains("Stale page item"), "{set}: {e}");
}
}
/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
/// the revert does not name the loaded one.
#[test]
@@ -2149,7 +2211,7 @@ fn page_items_report_their_available_members_as_their_own() {
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
app.hasOwnProperty('activeDocument')]);\
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
);
@@ -0,0 +1,169 @@
//! The script object model's document defaults for new art and `scaleFactor`.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::LineCap;
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// A 400 × 300 pt document with one rectangle, selected.
fn doc() -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
(s, id)
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
fn node(s: &Session, id: NodeId) -> crate::doc::Node {
s.active().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn a_wider_default_stroke_goes_to_the_next_path_drawn() {
let (mut s, picked) = doc();
let (look, steps) = (node(&s, picked).appearance, undo_steps(&s));
let wider = s.paint.stroke_width + 1.0;
let r = run(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth);").unwrap();
assert_eq!(r["log"][0].as_f64(), Some(wider));
assert_eq!(undo_steps(&s), steps, "a default alone is no undo step");
assert_eq!(node(&s, picked).appearance, look, "the selected path kept its stroke");
assert_eq!(s.new_art().stroke().unwrap().width, wider);
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(200, 100, 50, 50); vc.log(p.strokeWidth);");
assert_eq!(out.iter().map(Value::as_f64).collect::<Vec<_>>(), vec![Some(wider)]);
}
#[test]
fn a_bad_default_throws_and_changes_nothing() {
let (mut s, _) = doc();
let before = s.paint.clone();
for (source, name) in [
("app.activeDocument.defaultStrokeWidth = -1", "RangeError"),
("app.activeDocument.defaultStrokeWidth = 1001", "RangeError"),
("app.activeDocument.defaultStrokeWidth = 'wide'", "TypeError"),
("app.activeDocument.defaultStrokeMiterLimit = 0", "RangeError"),
("app.activeDocument.defaultStrokeCap = 'round'", "TypeError"),
("app.activeDocument.defaultStrokeJoin = 1", "TypeError"),
("app.activeDocument.defaultStrokeDashes = [0, 0]", "RangeError"),
("app.activeDocument.defaultStrokeDashes = '4 2'", "TypeError"),
("app.activeDocument.defaultStrokeDashOffset = 3", "Error"),
("app.activeDocument.defaultFillColor = 5", "TypeError"),
("var c = new RGBColor(); c.red = 300; app.activeDocument.defaultStrokeColor = c", "RangeError"),
("app.activeDocument.defaultFilled = 1", "TypeError"),
("app.activeDocument.defaultStrokeOverprint = 'yes'", "TypeError"),
] {
let out = log(&mut s, &format!("try {{ {source}; vc.log('ran'); }} catch (e) {{ vc.log(e.name); }}"));
assert_eq!(out, vec![json!(name)], "{source}");
assert_eq!(s.paint, before, "{source} changed new art");
}
}
#[test]
fn default_colors_and_flags_read_back_and_paint_the_next_path() {
let (mut s, picked) = doc();
let look = node(&s, picked).appearance;
let out = log(
&mut s,
"var d = app.activeDocument, c = new RGBColor(); c.red = 255;\
d.defaultFillColor = c; vc.log(d.defaultFillColor.typename); vc.log(d.defaultFillColor.red); vc.log(d.defaultFilled);\
d.defaultStroked = false; vc.log(d.defaultStroked); vc.log(d.defaultStrokeColor.typename);\
d.defaultStrokeColor = new GrayColor(); vc.log(d.defaultStroked);\
d.defaultFillColor = new NoColor(); vc.log(d.defaultFilled); d.defaultFilled = true; vc.log(d.defaultFilled);\
d.defaultFillColor = c;",
);
assert_eq!(out, vec![json!("RGBColor"), json!(255), json!(true), json!(false), json!("NoColor"), json!(true), json!(false), json!(true)]);
assert_eq!(node(&s, picked).appearance, look);
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap());
let ap = node(&s, id).appearance;
assert_eq!(ap.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
assert!(!ap.stroke_paint().is_none());
}
#[test]
fn default_stroke_options_read_back_and_a_same_value_runs_no_command() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeJoin = StrokeJoin.BEVELENDJOIN;\
d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2]; d.defaultStrokeDashOffset = 1;\
d.defaultStrokeOverprint = true; d.defaultFillOverprint = true;\
vc.log([d.defaultStrokeCap, d.defaultStrokeJoin, d.defaultStrokeMiterLimit, d.defaultStrokeDashes, d.defaultStrokeDashOffset,\
d.defaultStrokeOverprint, d.defaultFillOverprint]);",
);
assert_eq!(out, vec![json!(["StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 2], 1, true, true])]);
let st = s.new_art().stroke().unwrap().clone();
assert_eq!((st.cap, st.miter_limit, st.overprint), (LineCap::Round, 7.0, true));
let r = run(
&mut s,
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeMiterLimit = 7;\
d.defaultStrokeDashes = [6, 2]; d.defaultStrokeOverprint = true; d.defaultStrokeWidth = d.defaultStrokeWidth;\
d.defaultFillColor = d.defaultFillColor;",
)
.unwrap();
assert_eq!(r["slowestCommands"], json!([]), "the same values run no command");
// `{}` and `[]` give a solid line.
assert_eq!(log(&mut s, "var d = app.activeDocument; d.defaultStrokeDashes = {}; vc.log(d.defaultStrokeDashes.length);"), vec![json!(0)]);
}
#[test]
fn a_slightly_different_number_reaches_new_art() {
let (mut s, _) = doc();
log(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 1; d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2];");
log(
&mut s,
"var d = app.activeDocument; d.defaultStrokeWidth = 1.0000000005; d.defaultStrokeMiterLimit = 7.0000000005;\
d.defaultStrokeDashOffset = 0.0000000005;",
);
let st = s.new_art().stroke().unwrap().clone();
assert_eq!(st.width, 1.000_000_000_5);
assert_eq!(st.miter_limit, 7.000_000_000_5);
assert_eq!(st.dash.map(|d| d.offset), Some(0.000_000_000_5));
}
#[test]
fn an_rgb_default_in_a_cmyk_document_runs_no_command_the_second_time() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
let set = "var d = app.activeDocument, c = new RGBColor(); c.red = 200; c.green = 40; c.blue = 90; d.defaultFillColor = c;";
let first = run(&mut s, set).unwrap();
assert_ne!(first["slowestCommands"], json!([]), "the first assignment changes new art");
let again = run(&mut s, set).unwrap();
assert_eq!(again["slowestCommands"], json!([]), "the same RGB value runs no command");
}
#[test]
fn scale_factor_is_one_and_read_only() {
let (mut s, _) = doc();
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.scaleFactor); d.scaleFactor = 4; vc.log(d.scaleFactor);");
assert_eq!(out, vec![json!(1), json!(1)]);
}
#[test]
fn defaults_refuse_while_new_art_takes_the_selected_look() {
let (mut s, _) = doc();
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let before = s.paint.clone();
let out = log(
&mut s,
"try { app.activeDocument.defaultStrokeWidth = 9; } catch (e) { vc.log(e.message.indexOf('New Art Has Basic Appearance') >= 0); }",
);
assert_eq!(out, vec![json!(true)]);
assert_eq!(s.paint, before);
}
File diff suppressed because it is too large. Load diff
+49 -1
View File
@@ -5,7 +5,7 @@ use std::cell::Cell;
use serde_json::{Value, json};
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES};
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_GROWTH_BYTES, TEST_RESULT_BYTES};
use crate::*;
fn rect(x: i64) -> Value {
@@ -1371,6 +1371,54 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() {
assert_eq!(state(&s), before);
}
#[test]
fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() {
// The point change waits in the object model until the script ends.
let source = "app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, -4];";
let mut s = two_docs();
let start = s.documents()[1].doc.clone();
assert_eq!(run(&mut s, source).unwrap()["ok"], true);
let added = start.retained_bytes_each(&s.documents()[1].doc).1 as u64;
assert!(added >= 3, "{added}");
// The change goes past this allowance and stays within twice it.
TEST_GROWTH_BYTES.with(|g| g.set(Some(added * 2 / 3)));
let run_to_the_question = |s: &mut Session| {
s.script_frames = true;
run(s, source).unwrap();
for _ in 0..1_000 {
if s.script_waiting() {
break;
}
assert!(s.script_pump().is_none());
}
assert!(s.script_waiting());
assert!(s.script_pump().is_none());
assert!(s.script_running());
};
let mut s = two_docs();
let before = state(&s);
let undo = s.documents()[1].history.undo.len();
run_to_the_question(&mut s);
assert_eq!(state(&s), before);
s.script_continue();
assert!(!s.script_waiting());
let done = s.script_pump().expect("the run ends once it may go on");
assert_eq!(done.unwrap()["ok"], true);
assert_eq!(s.documents()[1].history.undo.len(), undo + 1);
assert_ne!(state(&s), before);
let mut s = two_docs();
let before = state(&s);
run_to_the_question(&mut s);
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
let ended = s.script_pump().expect("a stopped run ends");
TEST_GROWTH_BYTES.with(|g| g.set(None));
assert!(ended.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
assert!(!s.script_running());
assert_eq!(state(&s), before);
}
#[test]
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
TEST_GROWTH.with(|g| g.set(Some(20)));
+1 -1
View File
@@ -235,7 +235,7 @@ fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move);
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::SelectionMove);
assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow);
assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow);
}
+6 -3
View File
@@ -1478,9 +1478,12 @@ impl Session {
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
// with the Selection tool, the objects it would take.
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
for (path, color) in shown {
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
// One overlay per layer color, sharing the kept outlines.
if ge_on || self.tool.id() == "selection" {
let shown = crate::cmd::globaledit::highlights(self);
for (color, paths) in &shown.groups {
v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision });
}
}
if let Some((cmd, p)) = deferred_preview {
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
+6
View File
@@ -995,11 +995,17 @@ fn structured_junk() {
("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})),
("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})),
("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})),
("addon.arrange.offset", json!({"direction": "column", "gap": -1e6, "order": "position", "reverse": true})),
("addon.arrange.offset", json!({"direction": "diagonal", "gap": f64::MAX, "order": 3, "reverse": "x"})),
("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})),
("addon.arrange.replace", json!({"fit": "proportional", "keep": true})),
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
("addon.arrange.match", json!({"source": "key", "rotate": true})),
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
@@ -83,7 +83,8 @@ const INSIDE: &[(&str, &str)] = &[
"",
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \
PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \
ZOrderMethod",
),
("Application.", "prototype"),
@@ -107,8 +108,13 @@ const INSIDE: &[(&str, &str)] = &[
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
@@ -129,6 +135,25 @@ const INSIDE: &[(&str, &str)] = &[
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
),
("PathItems.", "prototype"),
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
("PathItem.", "prototype"),
(
"PathItem.prototype.",
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
strokeWidth strokeWidth= stroked stroked= translate",
),
("PathPoints.", "prototype"),
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
("PathPoint.", "prototype"),
(
"PathPoint.prototype.",
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
rightDirection= selected selected= typename",
),
("Tags.", "prototype"),
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
("Tag.", "prototype"),
@@ -150,8 +175,14 @@ const INSIDE: &[(&str, &str)] = &[
TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed",
),
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
("PointType.", "CORNER SMOOTH"),
("PolarityValues.", "NEGATIVE POSITIVE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
(
"",
@@ -282,9 +313,11 @@ const INSIDE: &[(&str, &str)] = &[
("TextFrame.prototype.", "contentVariable contentVariable="),
];
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem";
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
/// other than `PathItem`, and the color classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
SymbolItem cmykColor";
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
+54 -8
View File
@@ -338,32 +338,78 @@ fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>, laid: bool) -> Vec<
/// it, as far as strokes round type reach) as type the page draws. How many of the page's text
/// objects no made type takes, shown or not: none that holds a piece of the object has its words
/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`).
///
/// The page can draw two text objects as one word: a word and a letter set apart from it (a swash
/// "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. A word
/// left that is the last word of one text object holding the piece joined to the first word of
/// another that holds it and draws after it, along the first one's lines, is theirs
/// ([`joined_by_two`]).
fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> {
let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>();
// Each object's pieces of type, and the words of them that no made type holding it has yet.
let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> =
shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect();
let pieces: usize = objects.iter().map(|o| o.0.len()).sum();
if content.len().saturating_mul(pieces) > MAX_PAIRS {
return None;
}
let mut budget = MAX_PAIRS.checked_sub(content.len().checked_mul(pieces)?)?;
let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9);
for c in content {
let Content::Made(node, region, seen) = c else { continue };
// The made type holding each object, in order: where it draws and its words.
let mut holders: Vec<Vec<Arc<Holder>>> = vec![vec![]; objects.len()];
let mut seen_slots = Vec::new();
for (slot, c) in content.iter().enumerate() {
let Content::Made(node, region, _) = c else { continue };
// Hidden made type has no region: where it draws, shown, is its own box.
let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue };
let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() };
for (rects, words, held) in &mut objects {
let (spelled, holder) = match &node.kind {
NodeKind::Text(t) => {
let text = t.plain_text();
let [a, b, ..] = t.xf.as_coeffs();
(spelling(&text), Some(Arc::new((drawn.center(), (a, b), word_pieces(&text).map(spelling).filter(|w| !w.is_empty()).collect()))))
}
_ => (String::new(), None),
};
for ((rects, words, held), by) in objects.iter_mut().zip(&mut holders) {
if rects.iter().any(|r| holds(drawn, r)) {
*held = true;
*seen |= region.is_some();
if region.is_some() && seen_slots.last() != Some(&slot) {
seen_slots.push(slot);
}
words.retain(|w| !spelled.contains(w.as_str()));
by.extend(holder.clone());
}
}
}
for ((_, words, _), by) in objects.iter_mut().zip(&holders) {
if !words.is_empty() && !by.is_empty() {
// Each unmatched word can visit every ordered pair of holders, plus the first-holder scan.
budget = budget.checked_sub(words.len().checked_mul(by.len())?.checked_mul(by.len().checked_add(1)?)?)?;
words.retain(|w| !joined_by_two(w, by));
}
}
for slot in seen_slots {
if let Content::Made(_, _, seen) = &mut content[slot] {
*seen = true;
}
}
Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count())
}
/// A made text object that holds a piece of the page's type: the centre of where it draws, the
/// way its lines run (the first column of its transform) and its words ([`spelling`]).
type Holder = (Point, (f64, f64), Vec<String>);
/// Is `word` (a [`spelling`]) the last word of one of `by` joined to the first word of another of
/// them that draws after it, along the first one's lines? Each part is a whole word of its text
/// object, so a piece is never made up of bits of words.
fn joined_by_two(word: &str, by: &[Arc<Holder>]) -> bool {
by.iter().map(Arc::as_ref).any(|(at, (a, b), first)| {
let Some(head) = first.last().filter(|h| word.len() > h.len() && word.starts_with(h.as_str())) else { return false };
let tail = &word[head.len()..];
by.iter()
.map(Arc::as_ref)
.any(|(next, _, second)| (next.x - at.x) * a + (next.y - at.y) * b > 0.0 && second.first().is_some_and(|w| w == tail))
})
}
/// What goes into each of `infos`' slots when the file's text document can't make the type of every
/// slot that shows: type made from the text document (`made`) where it can, else the page's type that
/// the text document puts where the page has it, else the page's type in a copy that a layer's or
+32
View File
@@ -8663,3 +8663,35 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0);
assert!(!read, "the uncapped dimension must still match: {w:?}");
}
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
fn word_of_two_text_objects(fourteen: f64, twenty: f64) -> crate::import::Imported {
let stories = [("20\r", 0, (twenty, 8180.0), (0.0, 0.0), 0.0), ("14\r", 0, (fourteen, 8180.0), (0.0, 0.0), 0.0)];
let doc = text_document(&stories).replacen("/0 (Helvetica)", "/0 (SourceSans3-Regular)", 1);
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
let page = "0 1 0 0 setcmykcolor /SourceSans3-Regular findfont 14 scalefont setfont 20 61.5 moveto (2014) show";
import(&eps(page, &art)).unwrap()
}
/// The page can draw two text objects as one word: "20" and "14" set one after the other come out
/// of the page as one piece, "2014", that neither spells. The word is the last word of the one
/// joined to the first word of the one after it, so the page's type is theirs and nothing is noted
/// as left out.
#[test]
fn a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type() {
let r = word_of_two_text_objects(8161.5 + 13.916, 8161.5);
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
assert_eq!(texts, ["20", "14"], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings);
}
/// The two text objects the other way round ("14" before "20") don't make the page's "2014": its
/// word keeps the loss note.
#[test]
fn two_text_objects_the_other_way_round_arent_the_word_the_page_draws() {
let r = word_of_two_text_objects(8161.5, 8161.5 + 13.916);
assert!(r.warnings.iter().any(|w| w.contains("some of the page's type has no text object in the layers")), "{:?}", r.warnings);
}
+108 -3
View File
@@ -8,12 +8,16 @@
//! in and rebuilds the table, which has one entry per chunk.
//!
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
//!
//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`])
//! once it has been measured, until the list changes.
use std::borrow::Cow;
use std::fmt;
use std::ops::{Index, IndexMut, RangeBounds};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use kurbo::Rect;
use serde::{Deserialize, Serialize};
use crate::path::Anchor;
@@ -40,12 +44,49 @@ pub struct Anchors {
ends: Vec<usize>,
/// The number of anchors.
len: usize,
/// The box round every anchor's point and handles, once measured; emptied by every change.
control: OnceLock<Rect>,
}
thread_local! {
/// [`measured_control_anchors`] of this thread.
static MEASURED_CONTROL_ANCHORS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many anchors [`Anchors::control_bounds`] has read on this thread.
pub fn measured_control_anchors() -> u64 {
MEASURED_CONTROL_ANCHORS.get()
}
impl Anchors {
/// An empty list.
pub const fn new() -> Self {
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() }
}
/// The box round every anchor's point and handles, or `None` when the list is empty. The list
/// reads its anchors for it once, and again only after it has changed.
pub fn control_bounds(&self) -> Option<Rect> {
if self.len == 0 {
return None;
}
Some(*self.control.get_or_init(|| {
MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64));
let mut r: Option<Rect> = None;
for c in &self.chunks {
for a in c.iter() {
for p in [a.p, a.h_in, a.h_out] {
r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p)));
}
}
}
r.unwrap_or_default()
}))
}
/// Forget the measured [`Self::control_bounds`]: every change calls it.
fn changed(&mut self) {
self.control.take();
}
/// The number of anchors.
@@ -85,6 +126,7 @@ impl Anchors {
if i >= self.len {
return None;
}
self.changed();
let (c, o) = self.locate(i);
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
}
@@ -101,11 +143,13 @@ impl Anchors {
/// The first anchor to change.
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.first_mut()?).first_mut()
}
/// The last anchor to change.
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.last_mut()?).last_mut()
}
@@ -118,6 +162,7 @@ impl Anchors {
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
/// iterator reaches it.
pub fn iter_mut(&mut self) -> IterMut<'_> {
self.changed();
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
self.chunks.iter_mut().flat_map(chunk)
}
@@ -177,6 +222,7 @@ impl Anchors {
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
fn reindex(&mut self) {
self.changed();
self.chunks.retain(|c| !c.is_empty());
self.len = self.chunks.iter().map(|c| c.len()).sum();
let n = self.chunks.len();
@@ -193,6 +239,7 @@ impl Anchors {
/// Add `a` at the end.
pub fn push(&mut self, a: Anchor) {
self.changed();
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
_ => {
@@ -210,6 +257,7 @@ impl Anchors {
/// Remove the last anchor.
pub fn pop(&mut self) -> Option<Anchor> {
self.changed();
let last = self.chunks.last_mut()?;
let a = Arc::make_mut(last).pop();
if last.is_empty() {
@@ -489,6 +537,7 @@ impl Index<usize> for Anchors {
impl IndexMut<usize> for Anchors {
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
fn index_mut(&mut self, i: usize) -> &mut Anchor {
self.changed();
let (c, o) = self.locate(i);
&mut Arc::make_mut(&mut self.chunks[c])[o]
}
@@ -501,7 +550,7 @@ impl From<Vec<Anchor>> for Anchors {
}
let len = v.len();
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
Self { chunks, ends: Vec::new(), len }
Self { chunks, ends: Vec::new(), len, control: OnceLock::new() }
}
}
@@ -725,6 +774,8 @@ mod tests {
}
}
assert_eq!(a.len(), v.len(), "step {step}");
// The box kept from the step before is measured again after the edit.
assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}");
if step % 50 == 0 {
assert_eq!(a, v, "step {step}");
for i in 0..v.len() {
@@ -737,6 +788,60 @@ mod tests {
assert_eq!(a.get(v.len()), None);
}
/// The box of every anchor of `v` with its handles, measured anchor by anchor.
fn box_of(v: &[Anchor]) -> Option<Rect> {
let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
}
#[test]
fn control_bounds_read_the_anchors_once_until_they_change() {
let n = 1000;
let mut a = Anchors::from(line(n));
let read = measured_control_anchors;
let before = read();
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(read() - before, n as u64, "the first call reads every anchor");
let copy = a.clone();
for _ in 0..5 {
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(copy.control_bounds(), box_of(&line(n)));
}
assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor");
// Every change measures again, and only the list that changed.
let far = Point::new(-50.0, 900.0);
type Edit = fn(&mut Anchors, Point);
let edits: [(&str, Edit); 11] = [
("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)),
("index_mut", |a, p| a[4].h_in = p),
("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)),
("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)),
("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)),
("push", |a, p| a.push(Anchor::corner(p))),
("insert", |a, p| a.insert(1, Anchor::corner(p))),
("pop", |a, _| {
let _ = a.pop();
}),
("remove", |a, _| {
let _ = a.try_remove(0);
}),
("truncate", |a, _| a.truncate(10)),
("reverse", |a, _| a.reverse()),
];
for (k, (what, edit)) in edits.iter().enumerate() {
let p = Point::new(far.x - k as f64, far.y + k as f64);
assert!(a.control_bounds().is_some());
edit(&mut a, p);
let r = read();
assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}");
assert_eq!(read() - r, a.len() as u64, "after {what}: measured again");
}
assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box");
a.clear();
assert_eq!(a.control_bounds(), None);
}
#[test]
fn iterators_skip_and_count_as_a_slice_does() {
let v = line(1000);
+3 -4
View File
@@ -745,11 +745,10 @@ impl PathData {
}
bbox
}
/// Bounds including control handles (used for quick culling).
/// Bounds including control handles (used for quick culling). Each subpath keeps its own box
/// ([`Anchors::control_bounds`]) until its anchors change.
pub fn control_bounds(&self) -> Option<Rect> {
let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b))
}
pub fn transform(&mut self, a: Affine) {
for sp in &mut self.subpaths {
+1 -1
View File
@@ -801,7 +801,7 @@ fn digits_unnamed(text: &str) -> Vec<u8> {
out
}
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing `\u{FFFD}`. This subset font
/// has no character map of its own, but the font is installed: each digit is found by its outline
/// there, so the whole text stays one type object, with no outlines left behind.
#[test]
-30
View File
@@ -8,35 +8,5 @@
startup | Noto Sans Arabic | Regular
startup | Noto Sans Thai | Regular
startup | Noto Sans Georgian | Regular
background | Cairo | Regular
background | Tajawal | ExtraLight
background | Tajawal | Light
background | Tajawal | Regular
background | Tajawal | Medium
background | Tajawal | Bold
background | Tajawal | ExtraBold
background | Tajawal | Black
background | Almarai | Light
background | Almarai | Regular
background | Almarai | Bold
background | Almarai | ExtraBold
background | IBM Plex Sans Arabic | Thin
background | IBM Plex Sans Arabic | ExtraLight
background | IBM Plex Sans Arabic | Light
background | IBM Plex Sans Arabic | Regular
background | IBM Plex Sans Arabic | Medium
background | IBM Plex Sans Arabic | SemiBold
background | IBM Plex Sans Arabic | Bold
background | Noto Kufi Arabic | Regular
background | Amiri | Regular
background | Amiri | Italic
background | Amiri | Bold
background | Amiri | Bold Italic
background | Alexandria | Regular
background | Fustat | Regular
background | Reem Kufi | Regular
background | Aref Ruqaa | Regular
background | Aref Ruqaa | Bold
background | Gulzar | Regular
demand | NanumGothic | Regular
demand | Noto Sans Devanagari | Regular
+3 -2
View File
@@ -25,8 +25,9 @@ use crate::{Action, Overlay, PointerEvent, ToolContext};
pub const DIALOG: &str = "corners";
/// Widgets sit at least this far inside their corner along each side of a right angle (screen px;
/// √2 times it along the bisector, at any angle), further in once the radius is.
const MIN_INSET_PX: f64 = 10.0;
/// √2 times it along the bisector, at any angle), further in once the radius is. The canvas draws the
/// widgets at the framework's `CornerWidgets::INSET`, which the UI's tests hold equal to this value.
pub const MIN_INSET_PX: f64 = 10.0;
/// Corners with a side shorter than this on screen (px) hide their widgets.
const MIN_SIDE_PX: f64 = 3.0 * MIN_INSET_PX;
+2
View File
@@ -17,6 +17,8 @@ pub enum Cursor {
GroupSelection,
/// Alt-dragging a copy with the Selection or Direct Selection tool: a double arrowhead.
SelectionCopy,
/// The Selection arrow over movable artwork.
SelectionMove,
Move,
Crosshair,
ResizeH,
+10 -1
View File
@@ -129,11 +129,20 @@ shown_when = [
hotspot = "The arrow's tip."
look = "Arrow with a small x badge (nothing to select)."
[[cursor]]
id = "SelectionMove"
group = "Selection"
shown_when = [
"The Selection tool over a selected object or its movable source artwork, or over its visible centre point without Cmd/Ctrl held.",
"The Selection tool over artwork while Alt is held, before the copy drag begins.",
]
hotspot = "The arrow's tip."
look = "The Selection arrow with a small move badge."
[[cursor]]
id = "Move"
group = "Selection"
shown_when = [
"The Selection tool over a selected object, or over any object with Alt held (once an Alt-drag starts, SelectionCopy shows).",
"The shape tools over a selected object's centre point (Attributes › Show Center), before a press there moves it (while the drag runs the arrow is plain, SelectionCopy with Alt, ArrowHollow while it snaps).",
"Reshape over a path or while dragging.",
"Inside the Free Transform and Crop Image boxes.",
+5
View File
@@ -88,6 +88,11 @@ pub enum Overlay {
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
/// as the whole line does.
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
/// Thin solid outlines of many objects in one color (the objects Global Edit takes). Later calls
/// return the same `paths` with the same `revision` for as long as the outlines do not change, and
/// a new `revision` when they do. The host strokes them again only when `revision` or the view
/// changes.
Outlines { paths: std::sync::Arc<[BezPath]>, color: [u8; 3], revision: u64 },
/// A line segment (smart guide, handle line).
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
/// An anchor square: filled = selected.
+3 -3
View File
@@ -1552,7 +1552,7 @@ impl Tool for SelectionTool {
// take the pointer too (on a thin box the centre lies within a handle's reach), and with
// Cmd/Ctrl held the press selects the object behind instead.
if near_selected && !m.cmd && hit_center(cx, p, cx.point_tol()).is_some() {
return Cursor::Move;
return Cursor::SelectionMove;
}
// View → Snap to Point: over an anchor a press would grab the object by, the arrow turns
// hollow.
@@ -1560,11 +1560,11 @@ impl Tool for SelectionTool {
return Cursor::ArrowHollow;
}
if selected_source_hit(cx, p).is_some() {
return Cursor::Move;
return Cursor::SelectionMove;
}
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
return Cursor::Move;
return Cursor::SelectionMove;
}
return Cursor::Arrow;
}
+9 -9
View File
@@ -17,7 +17,7 @@ fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() {
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
for x in [75.0, 125.0] {
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}");
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::SelectionMove, "at {x}");
let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0));
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0));
@@ -45,7 +45,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
s.set([rect, ids[1]]);
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0));
@@ -55,7 +55,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap();
s.set([ids[1]]);
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}");
}
@@ -1042,7 +1042,7 @@ fn hidden_box_handles_take_no_press_while_anchors_are_selected() {
s.anchors.entry(id).or_default().insert((0, 1));
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::SelectionMove);
let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0));
assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}");
assert!(!crate::select::bbox_handle_at(&c, top_middle));
@@ -3006,9 +3006,9 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() {
let c = ToolContext { path_only: true, ..cx(&d, &s, &p) };
let centre = Point::new(150.0, 150.0);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::SelectionMove);
// Cmd/Ctrl selects the object behind, not the centre point, so the pointer says neither.
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::Move);
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::SelectionMove);
assert!(t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)).is_empty());
let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0));
assert_eq!(a.first(), Some(&Action::Begin("Move".into())), "{a:?}");
@@ -3102,7 +3102,7 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() {
assert!(hit_center(&c, centre, c.point_tol()).is_some());
let mut t = SelectionTool::default();
let cursor = t.cursor(&c, centre, Mods::default());
assert_ne!(cursor, Cursor::Move, "the guide's cursor, not the move arrow");
assert_ne!(cursor, Cursor::SelectionMove, "the guide's cursor, not the move arrow");
let down = t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y));
let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}");
@@ -3177,7 +3177,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
s.set(picked.iter().copied());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "{picked:?}");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "{picked:?}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
@@ -3218,7 +3218,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor");
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "every anchor");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "every anchor: {down:?}");
}
+1
View File
@@ -104,6 +104,7 @@ vectorcraft-testkit = { workspace = true }
vectorcraft-tools = { workspace = true, features = ["testing"] }
# A variable font built in code (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
wat = { workspace = true }
[build-dependencies]
+64 -3
View File
@@ -1,5 +1,6 @@
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and
//! Sort Objects,
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
@@ -22,19 +23,23 @@ use crate::menus::{Sep, c, cp};
/// Zoom to Selection: a view command, since the view is the interface's.
pub const ZOOM: &str = "addon.arrange.zoomSelection";
const GRID: &str = "addon.arrange.grid";
const OFFSET: &str = "addon.arrange.offset";
const REPLACE: &str = "addon.arrange.replace";
const SIZE: &str = "addon.arrange.size";
const MATCH: &str = "addon.arrange.match";
const OPACITY: &str = "addon.arrange.randomizeOpacity";
const SORT: &str = "addon.arrange.sort";
/// Each dialog's command and heading.
const DIALOGS: [(&str, &str); 5] = [
const DIALOGS: [(&str, &str); 7] = [
(GRID, "Arrange in Grid"),
(OFFSET, "Offset Objects"),
(REPLACE, "Replace with Top Object"),
(SIZE, "Set Size of Each"),
(MATCH, "Match Objects"),
(OPACITY, "Randomize Opacity"),
(SORT, "Sort Objects"),
];
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes.
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take.
const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6;
const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6;
/// The seeds the Randomize Opacity dialog offers.
@@ -56,10 +61,12 @@ const ATTRIBUTES: [(&str, &str); 7] = [
pub fn menu() -> Vec<Node> {
vec![
c("Arrange in Grid…", GRID),
c("Offset Objects…", OFFSET),
cp("Swap Objects", "addon.arrange.swap", json!({})),
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
c("Replace with Top Object…", REPLACE),
c("Set Size of Each…", SIZE),
c("Match Objects…", MATCH),
cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})),
c("Randomize Opacity…", OPACITY),
c("Sort Objects…", SORT),
@@ -69,8 +76,10 @@ pub fn menu() -> Vec<Node> {
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
@@ -116,6 +125,17 @@ fn grid_rows(lengths: LengthUnits) -> Vec<Param> {
]
}
fn offset_rows(lengths: LengthUnits) -> Vec<Param> {
let directions = [("row", "Row (Left to Right)"), ("column", "Column (Top to Bottom)")];
let orders = [("stacking", "Stacking Order"), ("position", "Position")];
vec![
choice("direction", "Direction:", &directions, "row"),
length("gap", "Gap:", 10.0, GAPS, lengths),
choice("order", "Order:", &orders, "stacking"),
check("reverse", "Reverse Order", false),
]
}
fn replace_rows() -> Vec<Param> {
let fits = [("keep", "Actual Size"), ("bounds", "Bounds"), ("proportional", "Bounds (Fit Proportionally)")];
vec![choice("fit", "Size:", &fits, "keep"), check("keep", "Keep Original", false), scale_strokes()]
@@ -134,6 +154,20 @@ fn size_rows(lengths: LengthUnits) -> Vec<Param> {
]
}
fn match_rows() -> Vec<Param> {
let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")];
let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")];
vec![
choice("source", "Match To:", &sources, "key"),
choice("size", "Size:", &sizes, "both"),
check("rotate", "Rotation", false),
check("stacking", "Stacking Order", false),
reference_param("reference", tl!("Reference Point")),
scale_strokes().enabled_when_in("size", ["width", "height", "both"]),
check("patterns", "Transform Patterns", false),
]
}
fn opacity_rows() -> Vec<Param> {
vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()]
}
@@ -156,6 +190,10 @@ fn grid_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&grid_rows(POINTS), fields))
}
fn offset_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&offset_rows(POINTS), fields))
}
fn replace_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&replace_rows(), fields))
}
@@ -173,6 +211,10 @@ fn size_params(fields: &DialogFields) -> Value {
Value::Object(params)
}
fn match_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&match_rows(), fields))
}
fn opacity_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&opacity_rows(), fields))
}
@@ -186,6 +228,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
let st = app.session.active()?;
let strokes = app.session.prefs.scale_strokes;
let key = st.selection.key.is_some();
let lengths = general_lengths(app);
let (rows, opening) = match command {
// A square grid to start with: as many columns as the square root of the count.
@@ -196,7 +239,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
"gapX": 10, "gapY": 10, "centerOnArtboard": false,
}),
),
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
// The key object while the selection has one, else the top object.
MATCH => (
match_rows(),
json!({
"source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false,
"reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles,
}),
),
// A new seed each time the document has changed, so running it again varies the result.
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
// The random order's seed (not shown): new whenever the document has changed, so each run
@@ -223,7 +275,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
let fields = form::fields_of(&rows, opening.as_object()?);
let opened = match command {
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| {
let chosen = fields.text("size").is_some_and(|size| size != "none")
|| fields.bool("rotate") == Some(true)
|| fields.bool("stacking") == Some(true);
let source = key || fields.text("source") != Some("key");
let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") };
dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields))
}),
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff. Show more