Merge main into feat/scripts-api-d6-save-export-open

This commit is contained in:
dotCooCoo committed 2026-11-30 10:55:42 -08:00
commit 8a5f206e3c
158 files changed
+5292 -1645

No files matched your search

+3 -1
View File
@@ -123,7 +123,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
+74
View File
@@ -0,0 +1,74 @@
"""Check a real installed release RPM and exercise the GUI control channel."""
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import time
import tempfile
def run_smoke(results):
requirements = (results / "rpm-requires.txt").read_text()
for capability in (
"libc.so.6()(64bit)",
"libm.so.6(GLIBC_2.35)(64bit)",
"libgcc_s.so.1()(64bit)",
"libxkbcommon.so.0()(64bit)",
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))",
):
if capability not in requirements.splitlines():
raise RuntimeError(f"Missing RPM requirement: {capability}")
version = subprocess.check_output(["vectorcraft-cli", "--version"], text=True)
(results / "cli-version.txt").write_text(version)
# Original fixture authored for this package smoke test; no external artwork.
fixture = results / "original-smoke.svg"
fixture.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="140">'
'<rect x="20" y="20" width="160" height="100" rx="12" fill="#2463eb"/>'
'<circle cx="100" cy="70" r="30" fill="#ffcc33"/></svg>')
token = secrets.token_hex(32)
with tempfile.TemporaryDirectory(prefix="vectorcraft-runtime-") as runtime, (results / "gui.log").open("w") as log:
env = dict(os.environ, VECTORCRAFT_NO_PREFS="1", XDG_RUNTIME_DIR=runtime,
VECTORCRAFT_CONTROL_TOKEN=token)
app = subprocess.Popen([
"vectorcraft", "--control", "32180", "--automation-read-root", str(results),
"--automation-write-root", str(results), str(fixture),
], stdout=log, stderr=subprocess.STDOUT, env=env)
try:
deadline = time.monotonic() + 90
while True:
if app.poll() is not None:
raise RuntimeError(f"GUI exited during startup: {app.returncode}")
try:
channel = socket.create_connection(("127.0.0.1", 32180), timeout=5)
break
except OSError:
if time.monotonic() >= deadline:
raise RuntimeError("GUI control channel did not become ready") from None
time.sleep(1)
channel.settimeout(30)
with channel, channel.makefile("rwb") as stream:
for request_id, method, params in (
(0, "auth", {"token": token}),
(1, "ui.inspect", {}),
):
stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode())
stream.flush()
response = json.loads(stream.readline())
(results / f"{method}.json").write_text(json.dumps(response, indent=2))
if response.get("id") != request_id or response.get("ok") is not True:
raise RuntimeError(f"GUI request failed: {method}")
finally:
app.terminate()
try:
app.wait(timeout=10)
except subprocess.TimeoutExpired:
app.kill()
app.wait()
if __name__ == "__main__":
run_smoke(Path("/results"))
@@ -0,0 +1,116 @@
"""Exercise failures that an installed-package happy-path check cannot reproduce."""
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import MagicMock, patch
spec = importlib.util.spec_from_file_location("rpm_smoke", Path(__file__).parents[1] / "release-rpm-smoke.py")
smoke = importlib.util.module_from_spec(spec)
spec.loader.exec_module(smoke)
class SmokeLifecycleTests(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.results = Path(self.folder.name)
(self.results / "rpm-requires.txt").write_text("\n".join([
"libc.so.6()(64bit)", "libm.so.6(GLIBC_2.35)(64bit)",
"libgcc_s.so.1()(64bit)", "libxkbcommon.so.0()(64bit)",
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))",
]))
self.app = MagicMock()
self.app.poll.return_value = None
self.channel = MagicMock()
self.stream = self.channel.makefile.return_value.__enter__.return_value
self.stream.readline.side_effect = [
b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n',
]
self.runtime = None
def launch(*args, **kwargs):
self.runtime = Path(kwargs["env"]["XDG_RUNTIME_DIR"])
self.assertTrue(self.runtime.is_dir())
return self.app
self.launch = self.start_patch(smoke.subprocess, "Popen", side_effect=launch)
self.start_patch(smoke.subprocess, "check_output", return_value="vectorcraft-cli 0.25.0\n")
self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel)
self.start_patch(smoke.time, "sleep")
def start_patch(self, owner, name, **kwargs):
patcher = patch.object(owner, name, **kwargs)
result = patcher.start()
self.addCleanup(patcher.stop)
return result
def assert_cleaned_up(self):
self.app.terminate.assert_called_once()
self.assertFalse(self.runtime.exists())
def test_success_records_inspection_and_removes_private_runtime(self):
smoke.run_smoke(self.results)
report = json.loads((self.results / "ui.inspect.json").read_text())
self.assertEqual(report["result"], {"window": "fixture"})
requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list]
self.assertEqual(requests[0]["method"], "auth")
self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"])
self.assert_cleaned_up()
def test_missing_runtime_dependency_prevents_launch(self):
(self.results / "rpm-requires.txt").write_text("")
with self.assertRaisesRegex(RuntimeError, "Missing RPM requirement"):
smoke.run_smoke(self.results)
self.launch.assert_not_called()
def test_child_exit_during_startup_is_a_failure(self):
self.app.poll.return_value = 1
self.app.returncode = 1
with self.assertRaisesRegex(RuntimeError, "exited during startup"):
smoke.run_smoke(self.results)
self.assert_cleaned_up()
def test_connection_is_retried_until_ready(self):
self.connect.side_effect = [OSError("not ready"), self.channel]
smoke.run_smoke(self.results)
self.assertEqual(self.connect.call_count, 2)
self.assert_cleaned_up()
def test_startup_timeout_stops_child(self):
self.connect.side_effect = OSError("not ready")
self.start_patch(smoke.time, "monotonic", side_effect=[0, 91])
with self.assertRaisesRegex(RuntimeError, "did not become ready"):
smoke.run_smoke(self.results)
self.assert_cleaned_up()
def test_auth_refusal_prevents_inspection(self):
self.stream.readline.side_effect = [b'{"id":0,"ok":false}\n']
with self.assertRaisesRegex(RuntimeError, "request failed: auth"):
smoke.run_smoke(self.results)
self.assertFalse((self.results / "ui.inspect.json").exists())
self.assert_cleaned_up()
def test_response_for_another_request_is_rejected(self):
self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', b'{"id":99,"ok":true}\n']
with self.assertRaisesRegex(RuntimeError, "request failed: ui.inspect"):
smoke.run_smoke(self.results)
self.assert_cleaned_up()
def test_malformed_response_still_stops_child(self):
self.stream.readline.side_effect = [b'not json\n']
with self.assertRaises(json.JSONDecodeError):
smoke.run_smoke(self.results)
self.assert_cleaned_up()
def test_unresponsive_child_is_killed_after_termination_timeout(self):
self.app.wait.side_effect = [subprocess.TimeoutExpired("vectorcraft", 10), 0]
smoke.run_smoke(self.results)
self.app.kill.assert_called_once()
self.assert_cleaned_up()
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -11,9 +11,9 @@ permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
# Enabled for automated scheduled producer completions on main.
if: >-
false && github.repository == 'storytold/vectorcraft' &&
github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+3 -2
View File
@@ -1,8 +1,9 @@
name: VectorCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors.
on:
schedule:
- cron: '30 6 * * *'
workflow_dispatch:
permissions:
+114
View File
@@ -0,0 +1,114 @@
name: Release RPM smoke
on:
workflow_dispatch:
inputs:
run-id:
description: Release run containing both RPM artifacts (empty selects the latest available pair)
type: string
default: ""
pull_request:
paths:
- .github/workflows/release-rpm-smoke.yml
- .github/scripts/release-rpm-smoke.py
- .github/scripts/tests/test_release_rpm_smoke.py
permissions: {}
jobs:
source:
permissions:
actions: read
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
run-id: ${{ steps.source.outputs.run-id }}
steps:
- id: source
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ inputs.run-id }}
run: |
candidates="$RUN_ID"
if [ -z "$candidates" ]; then
candidates=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow release.yml --branch release --limit 10 --json databaseId --jq '.[].databaseId')
fi
for candidate in $candidates; do
[[ "$candidate" =~ ^[0-9]+$ ]]
names=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$candidate/artifacts?per_page=100" --jq '.artifacts[] | select(.expired == false) | .name')
if grep -Fxq release-linux-x86_64 <<< "$names" && grep -Fxq release-linux-aarch64 <<< "$names"; then
printf 'run-id=%s\n' "$candidate" >> "$GITHUB_OUTPUT"
exit 0
fi
done
echo '::error::No release run has both Linux package artifacts available'
exit 1
smoke:
permissions:
contents: read
actions: read
needs: source
timeout-minutes: 25
strategy:
fail-fast: false
matrix:
platform:
- {arch: x86_64, runner: ubuntu-24.04}
- {arch: aarch64, runner: ubuntu-24.04-arm}
distro: [fedora, rocky, opensuse]
runs-on: ${{ matrix.platform.runner }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- name: Download the release packages
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ needs.source.outputs.run-id }}
ARCH: ${{ matrix.platform.arch }}
run: |
[[ "$RUN_ID" =~ ^[0-9]+$ ]]
mkdir -p packages results
gh run view "$RUN_ID" --json headSha,url > results/source.json
gh run download "$RUN_ID" --name "release-linux-$ARCH" --dir packages
sha256sum packages/*.rpm > results/rpm-sha256.txt
- name: Install and start the RPM on the target distribution
env:
DISTRO: ${{ matrix.distro }}
run: |
sudo apt-get update -qq
sudo apt-get install -y xvfb
Xvfb :99 -screen 0 1440x900x24 -ac -nolisten tcp > results/xvfb.log 2>&1 &
for _attempt in {1..20}; do
[ -S /tmp/.X11-unix/X99 ] && break
sleep 1
done
[ -S /tmp/.X11-unix/X99 ]
case "$DISTRO" in
fedora) image=fedora:latest ;;
rocky) image=rockylinux:10 ;;
opensuse) image=opensuse/tumbleweed:latest ;;
esac
docker pull "$image"
docker image inspect "$image" --format '{{json .RepoDigests}}' > results/container-digest.json
docker run --rm --ipc=host --name rpm-smoke -e DISTRO -e DISPLAY=:99 -e LIBGL_ALWAYS_SOFTWARE=1 \
-v /tmp/.X11-unix:/tmp/.X11-unix:ro -v "$PWD/packages:/packages:ro" \
-v "$PWD/results:/results" -v "$PWD/.github/scripts:/checks:ro" "$image" bash -euc '
cat /etc/os-release > /results/os-release.txt
if [ "$DISTRO" = opensuse ]; then
zypper --non-interactive refresh
zypper --non-interactive install python3 Mesa-dri Mesa-libEGL1 libX11-6 libXcursor1 libXi6 libXrandr2 libxkbcommon0 libxkbcommon-x11-0
zypper --non-interactive --no-gpg-checks install /packages/*.rpm
else
dnf -y install python3 mesa-dri-drivers mesa-libEGL libX11 libXcursor libXi libXrandr libxkbcommon libxkbcommon-x11
dnf -y --nogpgcheck install /packages/*.rpm
fi
rpm -qp --requires /packages/*.rpm > /results/rpm-requires.txt
python3 /checks/release-rpm-smoke.py
'
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: rpm-smoke-${{ matrix.distro }}-${{ matrix.platform.arch }}
path: results/
if-no-files-found: error
+1
View File
@@ -43,6 +43,7 @@ jobs:
app-name: vectorcraft
app-title: VectorCraft
macos-runner: macos-15
macos-split-build: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
+3
View File
@@ -21,4 +21,7 @@ jobs:
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
# archive stays within hosted-runner memory (craft-common-actions#333).
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
python-coverage-source: .github/scripts
python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py
secrets: inherit
Generated
+189 -178
View File
File diff suppressed because it is too large. Load diff
+52 -50
View File
@@ -4,55 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.25.0"
version = "0.25.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735", 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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
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 = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "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" }
@@ -192,22 +194,22 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "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" }
+1 -1
View File
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+1
View File
@@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true }
# frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and
# the update client.
craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] }
craft-nightly = { workspace = true }
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
egui = { workspace = true }
egui_extras = { workspace = true }
+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"]));
}
}
+79 -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)]
@@ -791,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),
@@ -808,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(),
@@ -816,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);
@@ -841,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.
+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));
+4 -3
View File
@@ -72,10 +72,11 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in
# Cargo.lock (tempfile, ui-egui), so this adds no new crate.
# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a
# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile,
# ui-egui), so this adds no new crate.
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true, features = ["std", "process"] }
rustix = { workspace = true, features = ["std", "process", "fs"] }
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
+5
View File
@@ -111,6 +111,7 @@ mod textedit;
pub use textedit::effective_kerning;
mod retype;
mod stepandrepeat;
pub mod textstyles;
pub(crate) mod textwrap;
pub(crate) mod threads;
@@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layerpanel::specs());
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(stepandrepeat::specs());
v.extend(effectcmd::specs());
v.extend(bevels::specs());
v.extend(wireframe::specs());
@@ -874,6 +876,9 @@ pub(crate) use vectorcraft_doc::range::parse_range;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
/// The faces and edges of Live Paint groups among objects that count with their group
/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer).
pub(crate) use paint::live_paint_covered;
#[cfg(test)]
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Brush",
[],
None,
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current → {ids}",
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; the brush settings of each path's top stroke (brush.objectOptions) are cleared, and clearing them is one undo step; when the brush is already current and applying it leaves every path as it was (its top stroke already has the brush, paint, a width above 0 and no settings of its own), nothing changes and no undo step is recorded → {ids}",
has_doc,
brush_apply
),
@@ -170,7 +170,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update); params and a newName that leave the brush as it is change nothing and record no undo step → {name}",
has_doc,
brush_options
),
+11 -4
View File
@@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
let stroke = stroke_paint(s);
s.edit("Apply Brush", |d, _| {
crate::cmd::colorcmds::edit_if_changed(s, "Apply Brush", |before, d| {
d.unknown.insert(brush::CURRENT_KEY.into(), json!(name));
apply_brush(d, &ids, &name, &stroke);
Ok(())
let changed = brush::current(before).as_deref() != Some(name.as_str()) || ids.iter().any(|id| before.node(*id) != d.node(*id));
Ok(((), changed))
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
@@ -213,6 +214,7 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt
}
}
/// Stores `lib` and applies `renames` as one undo step named `label`.
fn save_library(s: &mut Session, label: &str, mut lib: Vec<Brush>, renames: &[(String, Option<String>)]) -> Result<()> {
s.edit(label, |d, _| {
for (from, to) in renames {
@@ -503,8 +505,13 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
v["name"] = json!(name);
}
v["type"] = json!(lib[i].kind.type_id());
lib[i] = parse_brush(C, v)?;
let out = lib[i].name.clone();
let edited = parse_brush(C, v)?;
let out = edited.name.clone();
// Options that leave the brush as it is change nothing and add no undo step.
if new_name.is_none() && edited == lib[i] {
return Ok(json!({ "name": out }));
}
lib[i] = edited;
let rename = new_name.map(|nn| (name, Some(nn)));
save_library(s, "Brush Options", lib, rename.as_slice())?;
Ok(json!({ "name": out }))
+34 -7
View File
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
"{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
has_selection_guides_or_artboard_tool,
cut
),
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
"{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -996,7 +996,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
}
#[cfg(test)]
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let roots = roots_placed(&st.doc, ids, &paths, |_, _| false);
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
roots
})
@@ -1044,7 +1045,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
refuse_symbol_part(s)?;
let st = s.doc()?;
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
Ok(roots_placed(&st.doc, ids, &paths, |_, _| true))
}
/// The objects of `objects` that are in `doc`, in paint order as
/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One
/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after
/// `in_paint_order` walks the tree twice).
fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec<NodeId>, HashMap<NodeId, Vec<usize>>) {
let paths = doc.index_paths(objects.iter().copied());
let mut ids: Vec<NodeId> = objects.iter().copied().filter(|id| paths.contains_key(id)).collect();
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
(ids, paths)
}
/// [`selected_roots`] for the selected objects inside the isolated object `root`
@@ -1056,8 +1069,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
refuse_symbol_part(s)?;
let st = s.doc()?;
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root))
}
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
@@ -1071,6 +1085,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
let paths = doc.index_paths(ids.iter().copied());
roots_placed(doc, ids, &paths, keep_member)
}
/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already.
fn roots_placed(doc: &Document, ids: Vec<NodeId>, paths: &HashMap<NodeId, Vec<usize>>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// A compound-path member acts as its compound (compounds are one object).
let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
.into_iter()
@@ -1134,7 +1153,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
})
};
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound));
Ok((direct, roots))
}
@@ -1192,6 +1212,13 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
});
clip.source_artboard = board.map(|a| a.rect);
}
if let Some(value) = p.get("artboard") {
let board = value
.as_u64()
.and_then(|v| st.doc.artboards.get(index(v)))
.ok_or_else(|| bad("edit.copy", "`artboard` must be the index of an artboard of the document"))?;
clip.source_artboard = Some(board.rect);
}
clip.guides = guides;
s.clipboard = clip;
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
+30
View File
@@ -348,6 +348,36 @@ fn direct_selection_cut_timing() {
}
}
/// Finding the selected roots (for the menus, for Move and its siblings, for Copy and Cut, and
/// inside an isolated group) walks the tree once for the paint order and the roots together, in
/// paint order whatever order the objects were selected in.
#[test]
fn finding_the_selected_roots_walks_the_tree_once() {
let mut s = session(2_000, square);
let all = crate::tests_large_edits::layer(&s, 0);
let reversed: Vec<u64> = all.iter().rev().map(|id| id.0).collect();
s.execute("select.set", &json!({"ids": reversed})).unwrap();
type Find = fn(&Session) -> Vec<NodeId>;
let finds: [(&str, Find); 3] = [
("the selected roots", |s| selected_roots(s).unwrap()),
("the roots to transform", |s| selected_roots_to_transform(s).unwrap()),
("Copy's targets", |s| copy_cut_targets(s).unwrap().1),
];
for (what, find) in finds {
let walks = tree_walks();
assert!(find(&s) == all, "{what} in paint order");
assert_eq!(tree_walks() - walks, 1, "finding {what} walked the tree {} times", tree_walks() - walks);
}
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
s.execute("select.set", &json!({"ids": reversed})).unwrap();
// The first call also builds the lookup cache that the isolation check reads.
assert!(selected_roots_inside(&s, group, false).unwrap() == all, "the roots inside the group in paint order");
let walks = tree_walks();
assert!(selected_roots_inside(&s, group, false).unwrap() == all);
assert_eq!(tree_walks() - walks, 1, "finding the roots inside the group walked the tree {} times", tree_walks() - walks);
}
/// The selected roots are found once for a document version and its selected objects, however many enabled checks
/// read them, and found again after the selection changes, after an edit, and for another selection.
#[test]
+157 -9
View File
@@ -267,6 +267,8 @@ thread_local! {
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many objects [`matches`] looked at on this thread.
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Form {
@@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.forms.pass();
super::select::walk_selectable(d, st.isolation, |n| {
#[cfg(test)]
OBJECTS_WALKED.with(|c| c.set(c.get() + 1));
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
}
@@ -1075,34 +1079,178 @@ pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
out
}
/// [`similar`]'s outlines as of a document revision and the options they were found with.
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
/// [`similar`]'s outlines as of a document revision, with what they were found from.
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
/// [`similar`]'s outlines and what they were found from.
#[derive(Clone, Debug)]
pub struct Similar {
revision: u64,
options: Options,
/// The document, the one selected object and the isolated object they were found with.
doc: Arc<Document>,
key: NodeId,
isolation: Option<NodeId>,
out: Arc<Highlights>,
}
/// Before Global Edit starts: with one supported object selected, the outlines of the other
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
/// progress, or when fewer than two objects would be taken. Kept per document revision and
/// options, as finding them walks the whole document.
/// options, as finding them walks the whole document. After an edit that replaced only the
/// selected object, and left what the others are compared with as it was (a move), the outlines
/// found before are kept without a walk.
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
// Global Edit is refused while an object of a dynamic symbol instance's art is selected.
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() {
return NO_HIGHLIGHTS.clone();
}
let o = &s.global_edit_options;
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
&& *rev == st.revision
&& opts == o
let key = st.selection.objects[0];
if let Some(c) = &mut *st.similar_outlines.borrow_mut()
&& c.options == *o
&& c.key == key
&& c.isolation == st.isolation
&& (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key))
{
return out.clone();
c.revision = st.revision;
c.doc = st.doc.clone();
return c.out.clone();
}
let out = Highlights::new(match matches(s, o) {
Ok(m) if m.len() >= 2 => outlines(st, &m),
_ => vec![],
});
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
*st.similar_outlines.borrow_mut() =
Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() });
out
}
/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both?
/// True when the layers differ only in `key` and in the layers and groups that hold it (the same
/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the
/// rest of the document is the same. A group that holds `key` is never like it (its form holds
/// `key`'s and more), so the walk looks into it before and after alike.
fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool {
let mut found = None;
let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| {
a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art)
};
// Everything else in the document (artboards, symbol settings, editing modes) as it was: the
// symbols' art is compared on its own, as one copy when no edit changed it.
let rest = |d: &Document| {
let mut d = d.clone();
d.layers.clear();
d.symbols.clear();
d
};
if then.symbols.len() != now.symbols.len()
|| !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b))
|| rest(then) != rest(now)
|| !changed_only(&then.layers, &now.layers, key, &mut found)
{
return false;
}
found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes()))
}
/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way
/// to it? `found` takes the two versions of `key` when it changed.
fn changed_only<'a>(then: &'a [Arc<Node>], now: &'a [Arc<Node>], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool {
if then.len() != now.len() {
return false;
}
then.iter().zip(now).all(|(a, b)| {
if Arc::ptr_eq(a, b) {
return true;
}
if a.id != b.id {
return false;
}
if a.id == key {
return found.replace((a, b)).is_none();
}
match (holder_children(a), holder_children(b)) {
(Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found),
_ => false,
}
})
}
/// The objects in a layer or a group.
fn holder_children(n: &Node) -> Option<&[Arc<Node>]> {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children),
_ => None,
}
}
/// Are two versions of a layer or a group the same apart from the objects in them?
fn same_holder(a: &Node, b: &Node) -> bool {
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
let kinds = match (kind, &b.kind) {
(
NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images },
NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di },
) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di,
(NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c,
_ => false,
};
kinds
&& *id == b.id
&& *name == b.name
&& *visible == b.visible
&& *locked == b.locked
&& *opacity == b.opacity
&& *blend == b.blend
&& *isolate == b.isolate
&& *knockout == b.knockout
&& *knockout_shape == b.knockout_shape
&& *appearance == b.appearance
&& *bbox_angle == b.bbox_angle
&& *extras == b.extras
}
/// How far apart two versions of the selected object's form may lie, in its unit box, and how much
/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a
/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in
/// its unit box by a transform that includes the move), well within this.
const KEPT: f64 = 1e-12;
/// Are two versions of the selected object compared with the other objects in the same way by
/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective
/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in
/// them?
fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0);
fn same_look(a: &Node, b: &Node) -> bool {
fill_of(a) == fill_of(b)
&& stroke_of(a) == stroke_of(b)
&& match (a.children(), b.children()) {
(Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)),
(x, y) => x.is_none() && y.is_none(),
}
}
if !(supported(a) && supported(b)) {
return false;
}
let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false };
let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs());
let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) {
(Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()),
(x, y) => x.is_none() && y.is_none(),
};
f.tag == g.tag
&& f.symbols == g.symbols
&& f.points.len() == g.points.len()
&& f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT)
&& fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y))
&& sizes
&& same_look(a, b)
}
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
/// selected object, in their layer's color.
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
+4 -2
View File
@@ -1045,11 +1045,13 @@ impl Session {
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
// A link is refused: the script's gate does not check where it leads.
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
_ => {}
}
crate::file_access::check_read(&file).map_err(denied)?;
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
// Read without following a link, so a link put in the file's place since the check
// above is refused too.
crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some)
})?;
let Some(bytes) = read else { return Ok(None) };
// The color profiles the file carries are installed where missing, as opening it installs
+12
View File
@@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) {
}
}
/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound
/// path is read at the parent's place, without looking either object up by id.
pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) {
let Some((_, up)) = path.split_last() else { return };
if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) {
return;
}
if let Some(n) = d.node_mut_at(up) {
snap_object(n, sc);
}
}
/// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added
/// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity
/// mask, to the pixel grid. Objects the edit did not touch are not visited.
+68 -8
View File
@@ -66,10 +66,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling {
/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of
/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then.
pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<bool> {
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
transform_patterns_at(s, p, ids, &paths)
}
/// [`transform_patterns`] with `paths`, the places of `ids` in the document's tree, found already.
fn transform_patterns_at(s: &mut Session, p: &Value, ids: &[NodeId], paths: &std::collections::HashMap<NodeId, Vec<usize>>) -> Result<bool> {
let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles);
let d = &s.doc()?.doc;
let mut uses = false;
let paths = d.index_paths(ids.iter().copied());
for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) {
uses |= uses_pattern_with_masks(n);
}
@@ -152,7 +157,9 @@ fn apply_transform_moving_guides(
let areas = bool_or(p, "typeAreas", false);
let objects = transforms_objects(p);
let mut sc = if Scaling::factor(xf).is_some() { scaling(s, p) } else { Scaling::default() };
sc.patterns = transform_patterns(s, p, &ids)?;
// The places of `ids`, found in one walk for Transform Patterns and for the edit below.
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
sc.patterns = transform_patterns_at(s, p, &ids, &paths)?;
let c = xf.as_coeffs();
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
let delta = guides.unwrap_or(Vec2::new(c[4], c[5]));
@@ -174,8 +181,6 @@ fn apply_transform_moving_guides(
// An edit normally preserves the tree positions already found here. Settling an active
// typing session can change the document before the edit closure runs, so look up again then.
let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s));
let d = &s.doc()?.doc;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
let mut interpolate = None;
@@ -192,7 +197,11 @@ fn apply_transform_moving_guides(
if copy { vec![] } else { ids }
} else {
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
s.edit(label, |d, sel| {
// A move of whole objects, not of copies (which `reindex` covers): the document before it,
// and the moved objects as the transform left them, for [`moved_by`] to check after the edit.
let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?;
let mut held: Vec<(Vec<usize>, Arc<Node>)> = vec![];
let targets = s.edit(label, |d, sel| {
let mut targets = match &kept {
// The document becomes the snapshot with the kept copies, untransformed, and the
// loop below transforms only the copies.
@@ -229,9 +238,14 @@ fn apply_transform_moving_guides(
transform_node(n, xf, sc, objects);
}
}
// Holding them makes any later change to them copy them first, which `moved_by` sees.
if from.is_some() {
held = targets.iter().filter_map(|id| paths.get(id)).filter_map(|p| Some((p.clone(), node_arc(d, p)?))).collect();
}
if objects {
for id in &targets {
super::pixelgrid::keep_compound_aligned(d, *id, sc);
// The transforms above leave every object at its place, so `paths` still holds them.
for p in targets.iter().filter_map(|id| paths.get(id)) {
super::pixelgrid::keep_compound_aligned_at(d, p, sc);
}
// Moving all of the tile art moves the tile as far.
if let Some(before) = tile_art {
@@ -248,7 +262,10 @@ fn apply_transform_moving_guides(
targets.extend(d.transform_ruler_guides(sel, xf));
}
Ok(targets)
})?
})?;
let st = s.doc_mut()?;
st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5])));
targets
};
let st = s.doc_mut()?;
if st.interaction.is_none() {
@@ -266,6 +283,49 @@ fn apply_transform_moving_guides(
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// The node at index path `path` of `d`, shared.
fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
let (first, rest) = path.split_first()?;
let mut cur = d.layers.get(*first)?;
for &i in rest {
cur = cur.children()?.get(i)?;
}
Some(cur.clone())
}
/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved
/// objects as the transform left them (`held`, each with its index path). `None` unless every moved
/// object is still that node at its path, none is a member of a blend (whose spine follows its
/// members), and every object the selection shows, the key object and the key anchor's object
/// included, is a moved object or inside one. A pass after the transform that changes a moved
/// object, such as the one that snaps moved pixel-aligned objects to the pixel grid again
/// ([`super::pixelgrid::refresh`]), copies it first, so it is no longer that node. The checks read
/// the nodes at their paths and look nothing up by id.
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(Vec<usize>, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
let d = &st.doc;
let unchanged = |(p, n): &(Vec<usize>, Arc<Node>)| d.node_at(p).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
if held.is_empty() || !held.iter().all(unchanged) {
return None;
}
// The node at each path is the moved object, so its parent is the node one level up.
let in_blend = |p: &[usize]| p.split_last().and_then(|(_, up)| d.node_at(up)).is_some_and(|parent| matches!(parent.kind, NodeKind::Blend { .. }));
if held.iter().any(|(p, _)| in_blend(p)) {
return None;
}
let mut moved = std::collections::HashSet::new();
for (_, n) in held {
n.walk(&mut |c| {
moved.insert(c.id);
});
}
let sel = &st.selection;
let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id));
if !shown.all(|id| moved.contains(&id)) {
return None;
}
Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() })
}
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
+41 -4
View File
@@ -185,14 +185,27 @@ fn can_change_mask(s: &Session) -> std::result::Result<(), String> {
/// most one outermost object, which it masks with `ids` (a call's `ids` stand in for the selection
/// here). A targeted layer is one subject root however many objects it selects. `make` itself
/// refuses any single target in those modes, a layer included, so a selection with a target counts
/// as one object.
/// as one object. The check sorts the selection into paint order for its outermost objects only when it has one
/// subject root and no target.
fn can_make(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
let Some(st) = s.active() else { return Ok(()) };
let roots = super::appearance::subject_roots(s).map_or(0, |r| r.len());
let outermost = super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len();
let targeted = st.selection.target.is_some();
if roots == 1 && (outermost <= 1 || targeted) { super::maskedit::can_edit_mask(s) } else { Ok(()) }
if roots != 1 {
return Ok(());
}
let one = st.selection.target.is_some() || {
#[cfg(test)]
OUTERMOST_FOUND.set(OUTERMOST_FOUND.get() + 1);
super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len() <= 1
};
if one { super::maskedit::can_edit_mask(s) } else { Ok(()) }
}
#[cfg(test)]
thread_local! {
/// How many times [`can_make`] found the selection's outermost objects on this thread.
static OUTERMOST_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -485,6 +498,12 @@ impl Session {
_ => TransparencyInfo::default(),
}
}
/// The first of the objects the Transparency panel shows ([`TransparencyInfo::ids`]), without comparing their
/// values.
pub fn transparency_target(&self) -> Option<NodeId> {
transparency_targets(self, &Value::Null).ok()?.first().copied()
}
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
@@ -759,4 +778,22 @@ mod tests {
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(NodeId(a)).unwrap().extras().mask, d.node(NodeId(a)).unwrap().extras().mask);
}
/// Make Opacity Mask's check sorts the selection for its outermost objects only when the selection has one
/// subject root; with several roots it is enabled without that sort.
#[test]
fn the_make_check_sorts_only_a_selection_with_one_root() {
let (mut s, a, b) = session_with_two();
let found = || OUTERMOST_FOUND.get();
select(&mut s, &[a, b]);
let before = found();
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before, "two roots: no paint-order sort");
select(&mut s, &[a]);
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before + 1, "one root: the outermost objects are found");
s.execute("select.none", &json!({})).unwrap();
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before + 1, "no roots: no sort");
}
}
+3 -2
View File
@@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool {
impl DocState {
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group,
/// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document.
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
if self.selection_paints().is_some_and(|p| !p.in_live_paint()) {
return std::collections::HashSet::new();
}
live_paint_covered(&self.doc, ids)
self.live_paint_covered_kept(ids)
}
}
+52
View File
@@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() {
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
}
/// How many times this thread read the groups around selected objects for their Live Paint faces
/// and edges ([`DocState::live_paint_covered_kept`]).
fn cover_reads() -> usize {
crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get)
}
/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel
/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the
/// objects' groups once for each version of the document and selection, not once for each question.
/// A Live Paint group selected with one of its faces still counts the face with its group.
#[test]
fn live_paint_faces_are_looked_for_once_per_document_version() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect();
s.execute("select.all", &json!({})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record");
let ask = |s: &Session| {
for _ in 0..3 {
s.proxy_paints();
s.shown_stroke();
s.proxy_mixed();
s.active().unwrap().stroke_mixed();
}
};
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "one read for this version of the document");
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "an edit reads them again, once");
s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "another selection reads them again, once");
// A Live Paint group with one of its edges selected too: the edge counts with its group on every ask.
s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap();
let group = s.active().unwrap().selection.objects[0];
let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id;
s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap();
let st = s.active().unwrap();
let covered = live_paint_covered(&st.doc, &st.selection.objects);
assert!(covered.contains(&edge));
for _ in 0..2 {
assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered);
}
}
/// Random selections of a document with nested groups answer as a walk does.
#[test]
fn random_selections_match_a_walk_of_the_document() {
@@ -409,6 +409,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.slice.release",
"object.slice.select",
"object.slice.setRect",
"object.stepAndRepeat",
"object.tag.add",
"object.tag.remove",
"object.tag.removeAll",
+2
View File
@@ -725,6 +725,8 @@ impl Session {
for e in self.prefs.keep_folders(&mut p) {
log::warn!("{e}");
}
// Tool settings saved by an earlier version are updated once.
p.migrate_tool_settings();
// Saved gradient presets get names no built-in preset or other saved one has.
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
+141
View File
@@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
used.into_iter().map(|(_, u)| u).collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many objects [`several_colors`] read on this thread.
static SEVERAL_COLORS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read
/// until a second color turns up.
fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> bool {
struct Seen<'a> {
first: Option<ColorKey>,
several: bool,
patterns: Vec<&'a str>,
}
impl<'a> Seen<'a> {
fn read(&mut self, m: &'a Node) {
#[cfg(test)]
SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1));
let (first, several) = (&mut self.first, &mut self.several);
paints(
m,
&mut |c, _, _, _| {
let k = ColorKey::of(c);
match first {
None => *first = Some(k),
Some(f) => *several |= *f != k,
}
},
&mut self.patterns,
);
}
fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet<NodeId>>) {
if self.several || only.is_some_and(|o| !o.contains(&n.id)) {
return;
}
self.read(n);
for c in n.children().into_iter().flatten() {
self.read_tree(c, only);
if self.several {
return;
}
}
}
}
let mut seen = Seen { first: None, several: false, patterns: vec![] };
for n in ids.iter().filter_map(|id| d.node(*id)) {
seen.read_tree(n, only);
if seen.several {
return true;
}
}
let mut next = 0;
while !seen.several
&& let Some(&name) = seen.patterns.get(next)
{
next += 1;
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
let _ = a.try_walk(&mut |m| {
seen.read(m);
if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) }
});
if seen.several {
break;
}
}
}
seen.several
}
impl Session {
/// Whether the objects `recolor.colors` reads without `ids` use more than one color: the
/// selection, or with nothing selected the objects Select All takes. False without a document.
pub fn several_colors_used(&self) -> bool {
let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false };
self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref()))
}
}
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
/// add the patterns it is painted with to `patterns`.
@@ -2050,6 +2128,69 @@ mod tests {
assert!(has(&t, RED), "P100 read again at the top");
}
/// How many objects [`several_colors`] read on this thread.
fn several_reads() -> usize {
SEVERAL_COLORS_READS.with(std::cell::Cell::get)
}
/// Whether more than one color is used ([`Session::several_colors_used`]), checked against the
/// length of `recolor.colors`'s list, with how many objects the answer read.
fn several(s: &mut Session, what: &str) -> (bool, usize) {
let before = several_reads();
let several = s.several_colors_used();
let reads = several_reads() - before;
let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len);
assert_eq!(several, listed > 1, "{what}: {listed} colors listed");
(several, reads)
}
/// The Recolor quick action asks on every change whether the selection uses more than one
/// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included,
/// and the objects are read only until a second color turns up.
#[test]
fn several_colors_stop_at_the_second_color() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let ids: Vec<u64> = (0..30)
.map(|i| {
let id =
s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
id
})
.collect();
s.execute("select.all", &json!({})).unwrap();
assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read");
// A blue object in the middle: the objects are read up to it, from either end.
s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap();
let (found, reads) = several(&mut s, "a blue in the middle");
assert!(found && matches!(reads, 15 | 16), "{reads} objects read");
s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap();
assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color");
s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap();
assert!(!several(&mut s, "the red ones").0);
s.execute("select.none", &json!({})).unwrap();
assert!(several(&mut s, "Select All's objects").0);
// A red object filled with a pattern too: its tile's color counts.
for (tile, expect) in [(BLUE, true), (RED, false)] {
let filled = NodeId(ids[1]);
s.edit("t", |d, _| {
let art = square(d, 0.0, Paint::solid(tile));
d.patterns.retain(|p| p.name != "Tile");
d.patterns.push(PatternDef::new("Tile", vec![art]));
if let Some(n) = d.node_mut(filled) {
n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY });
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap();
assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}");
}
}
/// A pattern tile's symbol instances charge the same limit as the art around it.
#[test]
fn pattern_tiles_charge_the_symbol_limit() {
+214
View File
@@ -0,0 +1,214 @@
//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for
//! print-and-cut work (stickers, labels).
use serde_json::{Value, json};
use vectorcraft_geom::{Rect, Vec2, rotate_deg};
use super::edit::{copy_above, selected_roots};
use super::object::group_nodes;
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or};
use crate::EngineError;
use vectorcraft_doc::Scaling;
const CMD: &str = "object.stepAndRepeat";
const MAX_CELLS: usize = 10_000;
const EPS: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"object.stepAndRepeat",
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
}
/// Which cells of the grid are turned by 180°.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Alternate {
None,
Columns,
Rows,
}
/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first
/// cell's, and whether its copy is turned by 180° about the cell's center.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Cell {
pub row: usize,
pub col: usize,
pub dx: f64,
pub dy: f64,
pub turned: bool,
}
/// How many items of `size` with `gap` between them fit in `room` (all at least 0).
pub fn fit_count(room: f64, size: f64, gap: f64) -> usize {
if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS {
return 0;
}
(((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize
}
/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh`
/// inside `margin` on every side.
pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) {
let m = margin.max(0.0);
(fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx))
}
/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy`
/// between rows, in reading order.
pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec<Cell> {
(0..rows)
.flat_map(|row| (0..cols).map(move |col| (row, col)))
.map(|(row, col)| Cell {
row,
col,
dx: col as f64 * (w + gx),
dy: row as f64 * (h + gy),
turned: match alt {
Alternate::None => false,
Alternate::Columns => col % 2 == 1,
Alternate::Rows => row % 2 == 1,
},
})
.collect()
}
fn count_param(p: &Value, key: &str) -> Result<usize> {
match p.get(key).filter(|v| !v.is_null()) {
None => Ok(1),
Some(v) => v
.as_u64()
.filter(|n| (1..=MAX_CELLS as u64).contains(n))
.map(|n| n as usize)
.ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))),
}
}
fn sheet_param(p: &Value) -> Result<Option<Rect>> {
let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) };
let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number")));
let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?);
if w <= 0.0 || h <= 0.0 {
return Err(bad(CMD, "`sheet` needs a positive width and height"));
}
Ok(Some(Rect::new(x, y, x + w, y + h)))
}
fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?;
check_switches(p, &["patterns"], CMD)?;
let fill = switch_or(p, "fill", false, CMD)?;
let alt = match p.get("rotate").filter(|v| !v.is_null()) {
None => Alternate::None,
Some(v) => match v.as_str() {
Some("none") => Alternate::None,
Some("columns") => Alternate::Columns,
Some("rows") => Alternate::Rows,
_ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")),
},
};
let gap = super::f64_or(p, "gap", 0.0);
let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap));
let margin = super::f64_or(p, "margin", 0.0);
if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) {
return Err(bad(CMD, "gaps and margin must be finite"));
}
let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) };
let sheet = sheet_param(p)?;
let mut roots = selected_roots(s)?;
if roots.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let d = &s.doc()?.doc;
let cut = match p.get("cutId").filter(|v| !v.is_null()) {
None => None,
Some(v) => {
let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?);
let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| {
let mut found = false;
n.walk(&mut |c| found |= c.id == id);
found
});
if !held {
return Err(bad(CMD, "`cutId` must be part of the selection"));
}
Some(id)
}
};
let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]);
let b = d.bounds_of(&measured, false);
let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?;
let (w, h) = (b.width(), b.height());
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(EngineError::Other("the selection has no area to repeat".into()));
}
let anchor = if fill {
let sheet = sheet.or_else(|| {
let c = d.bounds_of(&roots, false).unwrap_or(b).center();
d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect)
});
let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?;
Some((sheet, margin.max(0.0)))
} else {
None
};
let (rows, cols) = match anchor {
Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy),
None => (rows, cols),
};
if rows == 0 || cols == 0 {
return Err(EngineError::Other("the selection does not fit the sheet".into()));
}
if rows.saturating_mul(cols) > MAX_CELLS {
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
}
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
let cells = layout(w, h, gx, gy, rows, cols, alt);
let center = b.center().to_vec2();
let place = |c: &Cell| -> Affine {
let t = Affine::translate(origin + Vec2::new(c.dx, c.dy));
if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t }
};
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
let ids = s.edit("Step and Repeat", |d, sel| {
if roots.len() > 1 {
roots = vec![group_nodes(d, &roots)?];
}
let mut copied: Vec<NodeId> = vec![];
let mut first = Affine::IDENTITY;
for c in &cells {
let m = place(c);
if c.row == 0 && c.col == 0 {
first = m;
continue;
}
let copies = copy_above(d, &roots, |_, _, n| {
n.transform(m, sc);
super::object::keep_pixel_aligned(n, sc);
})?;
copied.extend(copies);
}
if first != Affine::IDENTITY {
for id in &roots {
if let Some(n) = d.node_mut(*id) {
n.transform(first, sc);
super::object::keep_pixel_aligned(n, sc);
}
}
}
let mut out: Vec<NodeId> = roots.clone();
out.extend(copied);
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,178 @@
use serde_json::json;
use super::*;
const A4: (f64, f64) = (210.0, 297.0);
#[test]
fn fills_a4_with_50_by_30_items_and_3_gap() {
assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4));
assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3));
assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0));
}
#[test]
fn layout_places_cells_at_the_pitch_and_alternates_rotation() {
let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns);
assert_eq!(c.len(), 36);
let at = |r: usize, k: usize| c[r * 4 + k];
assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0));
assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0));
assert_eq!(c.iter().filter(|c| c.turned).count(), 18);
assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned);
let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows);
assert_eq!(rows.iter().map(|c| c.turned).collect::<Vec<_>>(), [false, false, true, true, false, false]);
assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned));
}
fn setup() -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
(s, id)
}
fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) {
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
(b.x0, b.y0, b.x1, b.y1)
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() {
let (mut s, _) = setup();
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s));
let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap();
assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3)));
assert_eq!(undo_steps(&s), steps + 1);
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0));
assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0));
assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(undo_steps(&s), steps);
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards.len(), before.artboards.len());
assert!(d.node(NodeId(ids[0])).is_some());
assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none()));
}
#[test]
fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() {
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36)));
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap();
assert_eq!(r["count"], json!(24));
let first = r["ids"][0].as_u64().unwrap();
assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0));
}
#[test]
fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3)));
assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0));
assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0));
assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0));
assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0));
}
#[test]
fn alternate_columns_turn_by_180_degrees_about_the_cell_center() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap();
let b0 = bounds(&s, id);
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1]));
assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6);
assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6);
let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind);
assert_ne!(tri(&s, ids[0]), tri(&s, ids[1]));
}
#[test]
fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() {
let (mut s, art) = setup();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap();
assert_eq!(r["count"], json!(3));
let d = &s.doc().unwrap().doc;
for id in r["ids"].as_array().unwrap() {
let n = d.node(NodeId(id.as_u64().unwrap())).unwrap();
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }));
let mut paths = 0;
n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
assert_eq!(paths, 2);
}
}
#[test]
fn rejects_bad_params_and_a_selection_that_does_not_fit() {
let (mut s, _) = setup();
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err());
assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err());
assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err());
assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err());
let mut e = Session::new();
e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(e.execute(CMD, &json!({})).is_err());
}
#[test]
fn fill_ignores_explicit_counts() {
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4)));
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
}
#[test]
fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() {
let gap = |aligned: bool| {
let (mut s, id) = setup();
if aligned {
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
}
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1]));
(c.0 - a.2, c.0 - a.0)
};
assert!((gap(false).0 - 0.5).abs() < 1e-9);
let pitch = gap(true).1;
assert!((pitch - pitch.round()).abs() < 1e-9);
}
#[test]
fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() {
let first_x = |sheet: Option<Value>| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
let mut p = json!({"fill": true, "cutId": cut});
if let Some(sh) = sheet {
p["sheet"] = sh;
}
let r = s.execute(CMD, &p).unwrap();
bounds(&s, r["ids"][0].as_u64().unwrap()).0
};
let default = first_x(None);
let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100})));
assert!((explicit - default - 100.0).abs() < 1e-9);
}
+167 -12
View File
@@ -4,6 +4,8 @@
//! resolves, for each area text object, the outlines of the wrap objects above it into
//! `TextObject::wrap` (text space); the layout engine subtracts them from each line's span.
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap};
@@ -17,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Text Wrap"],
None,
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}",
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a selected type object with another selected object above it in its layer is the text to wrap, not a wrap object, and loses a wrap it had; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids (the wrap objects), warning? (no area type lies below any of them)}",
has_selection,
make
),
@@ -27,13 +29,16 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap Options…",
["Object", "Text Wrap"],
None,
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects, leaving out the type selected below them as Make does (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
has_selection,
options
),
]
}
/// The warning Make gives when no area type lies below any of its wrap objects in their layer.
pub const NO_AREA_TYPE_BELOW: &str = "Text Wrap: no area type lies below these objects in their layer, so no text wraps around them. Move the objects above the area type with Object › Arrange › Bring to Front. Point type does not wrap.";
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
@@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? })
}
/// The type objects of `ids` that lie below another of `ids` in their layer: the text Make wraps
/// when the wrap objects and the type are selected together. Make leaves them out of the wrap
/// objects, and takes the wrap off any of them that has one.
fn type_to_wrap(d: &Document, ids: &[NodeId]) -> HashSet<NodeId> {
let wanted: HashSet<NodeId> = ids.iter().copied().collect();
// One pass in paint order: each selected type object with its layer and place, and the place of
// the topmost selected object other than a layer in each layer.
let mut texts = vec![];
let mut top: HashMap<usize, usize> = HashMap::new();
let mut at = 0usize;
for (layer, l) in d.layers.iter().enumerate() {
l.walk(&mut |n| {
if wanted.contains(&n.id) {
match n.kind {
NodeKind::Layer { .. } => {}
NodeKind::Text(_) => {
texts.push((n.id, layer, at));
top.insert(layer, at);
}
_ => {
top.insert(layer, at);
}
}
}
at += 1;
});
}
texts.into_iter().filter(|(_, layer, at)| top.get(layer).is_some_and(|t| t > at)).map(|(id, _, _)| id).collect()
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?;
let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?;
s.edit("Make Text Wrap", |d, _| {
for id in &ids {
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
if matches!(n.kind, NodeKind::Layer { .. }) {
let (objects, text, changed) = {
let d = &s.doc()?.doc;
let text = type_to_wrap(d, &ids);
let objects: Vec<NodeId> = ids.iter().copied().filter(|i| !text.contains(i)).collect();
for id in &objects {
if d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. })) {
return Err(EngineError::Other("layers can't be wrap objects".into()));
}
n.extras_mut().wrap = Some(w);
}
Ok(())
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
let changed = objects.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap != Some(w)))
|| text.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap.is_some()));
(objects, text, changed)
};
if changed {
s.edit("Make Text Wrap", |d, _| {
for id in &objects {
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = Some(w);
}
for id in &text {
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = None;
}
Ok(())
})?;
}
let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::<Vec<_>>() });
let mut wraps = false;
vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
if !wraps {
out["warning"] = json!(NO_AREA_TYPE_BELOW);
}
Ok(out)
}
fn release(s: &mut Session, p: &Value) -> Result<Value> {
@@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
fn options(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.options")?;
let current = {
// The type selected below the wrap objects is the text they wrap, as in Make.
let (ids, current) = {
let d = &s.doc()?.doc;
ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default()
let text = type_to_wrap(d, &ids);
let ids: Vec<NodeId> = ids.into_iter().filter(|i| !text.contains(i)).collect();
let current = ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default();
(ids, current)
};
if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) {
return Ok(json!({ "offset": current.offset, "invert": current.invert }));
}
let w = wrap_param(p, current, "object.textWrap.options")?;
let changed = {
let d = &s.doc()?.doc;
ids.iter().any(|i| d.node(*i).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. }) && n.extras().wrap != Some(w)))
};
if !changed {
return Ok(json!({ "offset": w.offset, "invert": w.invert }));
}
s.edit("Text Wrap Options", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id)
@@ -287,6 +353,95 @@ mod tests {
assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true}));
}
fn wrap_of(s: &Session, id: u64) -> Option<vectorcraft_doc::TextWrap> {
s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap
}
fn area_type(s: &mut Session) -> u64 {
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(300), "size": 12, "area": {"width": 400, "height": 400}}))
.unwrap()["id"]
.as_u64()
.unwrap()
}
fn ellipse(s: &mut Session) -> u64 {
s.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()
}
/// Make with the wrap object and the area type below it selected together wraps the type: the
/// type is the text to wrap, not another wrap object (#3211).
#[test]
fn make_with_the_area_type_selected_wraps_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let t = area_type(&mut s);
let plain = lines(&s, t);
let c = ellipse(&mut s);
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(r, json!({"ids": [c]}), "{r}");
assert!(wrap_of(&s, c).is_some());
assert!(wrap_of(&s, t).is_none(), "the area type became a wrap object");
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
// Make again with the same options changes nothing and records no undo step.
let steps = s.doc().unwrap().history.undo.len();
assert_eq!(s.execute("object.textWrap.make", &json!({})).unwrap(), json!({"ids": [c]}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// Text Wrap Options with both still selected sets the wrap object's options only, and the
// type keeps wrapping; the same options again record no undo step.
let wrapped = lines(&s, t);
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap()["offset"], json!(30.0));
assert_eq!(wrap_of(&s, c).map(|w| w.offset), Some(30.0));
assert!(wrap_of(&s, t).is_none(), "Options made the area type a wrap object");
assert_ne!(lines(&s, t), wrapped, "the type did not follow the new offset");
assert_ne!(lines(&s, t), plain);
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
s.execute("edit.undo", &json!({})).unwrap();
// One undo takes the wrap off again.
s.execute("edit.undo", &json!({})).unwrap();
assert!(wrap_of(&s, c).is_none());
assert_eq!(lines(&s, t), plain);
}
/// Make with the object below the area type warns that no text wraps. After Bring to Front,
/// Make with both selected wraps the type, and the type that the first Make made a wrap object
/// is the text to wrap again (#3211).
#[test]
fn make_warns_when_the_object_is_below_the_type_and_wraps_after_bring_to_front() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let c = ellipse(&mut s);
let t = area_type(&mut s);
let plain = lines(&s, t);
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(r["warning"], json!(super::NO_AREA_TYPE_BELOW), "{r}");
assert_eq!(lines(&s, t), plain);
s.execute("select.set", &json!({"ids": [c]})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
assert!(wrap_of(&s, t).is_none(), "the area type is still a wrap object");
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
}
/// Point type below a wrap object does not wrap, so Make warns.
#[test]
fn make_warns_over_point_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let p = s.execute("text.create", &json!({"x": 0, "y": 100, "text": "point type", "size": 12})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 80, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r, p]})).unwrap();
let out = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(out["warning"], json!(super::NO_AREA_TYPE_BELOW), "{out}");
assert!(wrap_of(&s, r).is_some());
assert!(wrap_of(&s, p).is_none(), "the point type became a wrap object");
}
#[test]
fn text_flows_on_both_sides_of_a_centred_object() {
let mut s = Session::new();
+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"),
+53
View File
@@ -203,6 +203,36 @@ pub struct DocState {
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
pub(crate) selection_record: Option<SelectionRecord>,
/// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live
/// Paint group among, with the document it read. Not saved.
outside_live_paint: std::cell::RefCell<Option<OutsideLivePaint>>,
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
/// Not saved.
pub moved: Option<Moved>,
}
/// Objects that hold no face or edge of a Live Paint group that counts with its group
/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as
/// [`EmptyArtboards::doc`] holds it.
#[derive(Clone, Debug)]
struct OutsideLivePaint {
doc: std::sync::Weak<Document>,
ids: Vec<NodeId>,
}
/// A move of whole objects that took document `from` to document `to`: each object the selection
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
/// they follow, no pass after the edit). A view that drew the selection of `from` can
/// move what it drew by `by` instead of building it again. It holds the documents as
/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches.
#[derive(Clone, Debug)]
pub struct Moved {
pub from: std::sync::Weak<Document>,
pub to: std::sync::Weak<Document>,
pub by: vectorcraft_geom::Vec2,
/// The selection the move was made with, which is also the selection after it.
pub selection: Selection,
}
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
@@ -302,6 +332,8 @@ thread_local! {
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread.
pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -522,6 +554,8 @@ impl DocState {
measured_in_own: None,
inline_resolved: None,
selection_record: None,
outside_live_paint: Default::default(),
moved: None,
}
}
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
@@ -539,6 +573,25 @@ impl DocState {
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
self.selection_record().and_then(|r| r.paints.as_ref())
}
/// The faces and edges of Live Paint groups among `ids` that count with their group
/// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and
/// these objects, so the proxies and the Stroke panel, which ask on every frame, read the
/// objects' groups once after an edit.
pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids;
if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) {
return std::collections::HashSet::new();
}
#[cfg(test)]
LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1));
let covered = cmd::live_paint_covered(&self.doc, ids);
if covered.is_empty()
&& let Ok(mut k) = self.outside_live_paint.try_borrow_mut()
{
*k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() });
}
covered
}
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
/// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same
/// document: the objects that leave the selection are taken out of its paints and the objects
+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)]
+1 -1
View File
@@ -512,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+36
View File
@@ -438,6 +438,12 @@ pub struct Prefs {
/// resetting the preferences keeps them; `tool.setOption` edits them.
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub tool_settings: std::collections::BTreeMap<String, serde_json::Map<String, Value>>,
/// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores
/// or updates a tool setting, 0 while none is stored and in preferences saved without one.
/// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog
/// field: resetting the preferences keeps it.
#[serde(default, skip_serializing_if = "is_zero")]
pub tool_settings_version: u32,
/// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local
/// library, not a Preferences dialog field: resetting the preferences keeps it;
/// `perspective.presets.*` edit it.
@@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
/// The range of the Hold Shortcut Delay, in seconds.
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]).
/// Version 1 makes Color Swatches the Shape Builder's Pick Color From.
pub const TOOL_SETTINGS_VERSION: u32 = 1;
fn is_zero(v: &u32) -> bool {
*v == 0
}
impl Prefs {
/// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before
/// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was
/// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a
/// version newer than this one is kept.
pub fn migrate_tool_settings(&mut self) {
if self.tool_settings_version < 1
&& let Some(saved) = self.tool_settings.get_mut("shapeBuilder")
&& saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork")
{
saved.insert("pickColorFrom".into(), Value::from("swatches"));
}
self.mark_tool_settings_current();
}
/// Record that [`Self::tool_settings`], when any is stored, is in this version's form.
pub(crate) fn mark_tool_settings_current(&mut self) {
if !self.tool_settings.is_empty() {
self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION);
}
}
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
@@ -672,6 +707,7 @@ impl Default for Prefs {
use_registration_point_for_symbol: false,
show_on_shape_creation: false,
tool_settings: Default::default(),
tool_settings_version: 0,
perspective_presets: vec![],
blend_options: None,
perspective_widget: Default::default(),
+93 -6
View File
@@ -49,6 +49,9 @@
//! `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
//! in the object.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
@@ -173,7 +176,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// written yet, how many times each path's points went stale and each path as the run last saw its
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
/// `app.selectTool` chose last.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
@@ -210,6 +214,7 @@ pub(super) struct State {
preset_bytes: Cell<u64>,
preset_limit: u64,
vars: variables::Handles,
tool: Cell<Option<&'static str>>,
}
impl State {
@@ -222,6 +227,12 @@ impl State {
pub(super) fn saving(&self) -> bool {
self.saving.get()
}
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
/// when the run ends without an error.
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
self.tool.get()
}
}
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
@@ -847,12 +858,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
/// hidden or locked.
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
/// changes are undone as well.
fn on_doc<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
}
/// The steps of [`on_doc`].
fn on_doc_steps<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before, layer, activated) = {
let s = h.session.borrow();
@@ -1024,6 +1047,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Bool(open))
}
/// The start of the tool names that scripts pass to `app.selectTool`, as the list at
/// <https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942> gives them.
const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass
/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the
/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's
/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own.
const TOOL_NAMES: &[(&str, &str)] = &[
("Select Tool", "selection"),
("Direct Select Tool", "directSelection"),
("Direct Object Select Tool", "groupSelection"),
("Direct Lasso Tool", "lasso"),
("Path Type Tool", "typeOnPath"),
("Vertical Path Type Tool", "verticalTypeOnPath"),
("Line Tool", "lineSegment"),
("Shape Construction Regular Polygon Tool", "polygon"),
("Shape Construction Star Tool", "star"),
("Shape Construction Spiral Tool", "spiral"),
("Brush Tool", "paintbrush"),
("Freehand Tool", "pencil"),
("Freehand Smooth Tool", "smooth"),
("Freehand Erase Tool", "pathEraser"),
("Corner Join Tool", "join"),
("Knife Tool", "knife"),
("New Twirl Tool", "twirl"),
("Cyrstallize Tool", "crystallize"),
("Planar Paintbucket Tool", "livePaintBucket"),
("Planar Face Select Tool", "livePaintSelection"),
("Mesh Editing Tool", "mesh"),
("Gradient Vector Tool", "gradient"),
("Crop Tool", "artboard"),
("Slice Select Tool", "sliceSelection"),
("Scroll Tool", "hand"),
("Page Tool", "printTiling"),
];
/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the
/// list [`TOOL_NAME_PREFIX`] cites.
fn tool_named(name: &str) -> Option<&'static str> {
let tools = || vectorcraft_tools::catalog::all_tools();
if let Some(t) = tools().find(|t| t.id == name || t.label == name) {
return Some(t.id);
}
let rest = name.strip_prefix(TOOL_NAME_PREFIX)?;
if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) {
return vectorcraft_tools::tool_info(id).map(|t| t.id);
}
tools().find(|t| t.label == rest).map(|t| t.id)
}
/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The
/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar
/// does; the tool chosen last in a run is the one that counts. A name no tool has throws.
fn app_select_tool(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) };
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the tool name is too long".into()));
}
let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?;
h.dom.tool.set(Some(id));
Ok(Data::Bool(true))
}
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
/// strings are the ones
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
@@ -2227,9 +2313,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
// A value the getter reports for the item's opacity sends the opacity it has, and
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
// A value the getter reports for the item's opacity runs no command, unless the item is a graph
// mark or label whose graph keeps another opacity for its series or kind: then the opacity the
// item has is sent, and replaces the one the graph keeps.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
@@ -2243,7 +2329,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if now.is_none() || keeps_other {
refuse_protected_edit(h, item)?;
}
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)}))
}
/// The members of `BlendModes` with the blend mode each one names.
@@ -2845,6 +2931,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
("redraw", method(l, app_redraw), returns("undefined", &[])),
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
("undo", method(l, app_undo), returns("undefined", &[])),
("redo", method(l, app_redo), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
+8
View File
@@ -2647,7 +2647,15 @@ impl Session {
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
}
close_run(self, host, &mut report, console::Ending::Finished);
let tool = host.dom.chosen_tool();
self.end_job(job, false);
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
if let Some(id) = tool
&& let Err(e) = self.select_tool(id, self.last_view)
{
report["toolError"] = json!(e.to_string());
}
self.script_report = Some(report.clone());
Ok(report)
}
+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,
+46
View File
@@ -219,6 +219,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
Ok(bytes)
}
/// What [`read_capped_plain`] tells a path that is not a plain file.
pub(crate) const NOT_PLAIN: &str = "not a plain file";
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
/// is refused with [`NOT_PLAIN`] rather than read.
pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result<Vec<u8>, String> {
let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) {
Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(),
_ => e.to_string(),
})?;
let m = file.metadata().map_err(|e| e.to_string())?;
if !m.file_type().is_file() || reparse_point(&m) {
return Err(NOT_PLAIN.to_string());
}
let mut bytes = vec![];
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
if bytes.len() as u64 > max {
return Err(too_large(max));
}
Ok(bytes)
}
/// `path` opened for reading, without following a link there. A pipe put in its place does not hold
/// the open up.
#[cfg(unix)]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::unix::fs::OpenOptionsExt;
let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK;
std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path)
}
/// `path` opened for reading; a link or junction there is opened itself, not its target.
#[cfg(windows)]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::windows::fs::OpenOptionsExt;
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)
}
#[cfg(not(any(unix, windows)))]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
std::fs::File::open(path)
}
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
/// [`Session::finish_plugin_loads`] install.
pub(crate) enum PluginLoad {
+1
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;
+71
View File
@@ -913,6 +913,77 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() {
assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err());
}
/// `brush.options` that leaves the brush as it is changes neither the document nor its revision,
/// and records no undo step, whether the library is stored or still the defaults.
#[test]
fn brush_options_that_change_nothing_record_no_undo_step() {
let mut s = session();
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
s.execute("brush.options", &json!({"name": "Arrow", "params": {}})).unwrap();
assert_eq!(state(&s), before, "unchanged options of a default library change nothing");
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 110.25}})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a changed option is one undo step");
let before = state(&s);
for p in [
json!({"name": "Arrow"}),
json!({"name": "Arrow", "params": {}}),
json!({"name": "Arrow", "params": {"width": 110.25}}),
json!({"name": "Arrow", "newName": " Arrow "}),
json!({"name": "Arrow", "newName": ""}),
] {
assert_eq!(s.execute("brush.options", &p).unwrap()["name"], "Arrow");
assert_eq!(state(&s), before, "{p} changes nothing");
}
s.execute("brush.options", &json!({"name": "Arrow", "newName": "Arrow 2"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
}
/// `brush.apply` of the brush that the strokes and the current brush already have changes neither
/// the document nor its revision, and records no undo step.
#[test]
fn brush_apply_that_changes_nothing_records_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1);
let before = state(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(state(&s), before, "applying the brush again changes nothing");
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "making the brush current again is one undo step");
assert_eq!(s.execute("brush.list", &json!({})).unwrap()["current"], "Charcoal");
let b = rect(&mut s, 80.0, 10.0, 50.0, 50.0);
let steps = undo_steps(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0, b.0]})).unwrap();
assert_eq!((brush_of(&s, a).as_deref(), brush_of(&s, b).as_deref()), (Some("Charcoal"), Some("Charcoal")));
assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step");
}
/// Applying the current brush again to a stroke with settings of its own clears them as one undo step.
#[test]
fn brush_apply_clears_object_options_as_one_undo_step() {
let mut s = session();
let a = line(&mut s);
select(&mut s, &[a]);
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap();
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
let steps = undo_steps(&s);
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
assert_eq!(own_options(&s, a), json!({}), "applying the brush clears the stroke's own settings");
assert_eq!(undo_steps(&s), steps + 1, "clearing the settings is one undo step");
}
/// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name
/// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone.
#[test]
+29 -1
View File
@@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo
}
/// The Shape Builder tool sends the point where the drag started first and the point where it
/// ended last, so a drag from the hole into the square takes the square's look.
/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the
/// square's look.
#[test]
fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
let mut s = session();
@@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
select_ids(&mut s, &bars.iter().copied().chain([red]).collect::<Vec<_>>());
let v = ViewInfo::default();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap();
@@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() {
let v = ViewInfo::default();
s.select_tool("shapeBuilder", v).unwrap();
let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count();
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging");
let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true});
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap();
@@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() {
assert_eq!(s.paint.fill, before, "the cancel puts the fill back");
}
/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a
/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape
/// is not the red or blue of the art.
#[test]
fn shape_builder_default_merge_fills_with_the_picked_fill() {
let v = ViewInfo::default();
for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] {
let mut s = session();
two(&mut s);
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap();
s.select_tool("shapeBuilder", v).unwrap();
s.execute("paint.setFill", &pick).unwrap();
let picked = s.paint.fill.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
let (cmd, params) = s.journal.last().unwrap().clone();
assert_eq!((cmd.as_str(), &params["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}");
let d = &s.doc().unwrap().doc;
let fills: Vec<Paint> = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect();
assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill");
}
}
/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder
/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient.
#[test]
+202 -1
View File
@@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged");
sel(&mut s, &[copies[0]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
sel(&mut s, &[copies[1]]);
@@ -156,6 +156,207 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
}
#[test]
fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
// The outlines `highlights` gives, and how many objects it looked at for them.
let shown = |s: &Session| {
let before = walked();
let out = highlights(s);
(out, walked() - before)
};
// The outlines in each layer color.
let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::<Vec<_>>();
// The outlines a walk finds, the options set again so that nothing is kept.
let fresh = |s: &mut Session| {
let size = s.global_edit_options.size;
s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap();
highlights(s);
s.execute("select.globalEditOptions", &json!({"size": size})).unwrap();
let before = walked();
let out = highlights(s);
assert!(walked() > before, "a walk");
paths(&out)
};
let mut s = session();
let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3);
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect();
sel(&mut s, &[key]);
let (first, n) = shown(&s);
assert_eq!(first.len(), 39);
assert!(n >= 40, "the first preview walks every object");
// The move rounds the form in its unit box differently; the same objects are like it.
s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap();
let (out, n) = shown(&s);
assert_eq!(n, 0, "a move of the selected object alone compares the others as before");
assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked");
assert_eq!(paths(&out), fresh(&mut s));
// Another object moved: it is shown where it is now.
sel(&mut s, &[copies[0]]);
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
sel(&mut s, &[key]);
let (out, n) = shown(&s);
assert!(n > 0, "another object changed");
let moved = node(&s, copies[0]).stroke_path().unwrap();
assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
assert_eq!(paths(&out), fresh(&mut s));
// The selected object took another shape: none of the squares is like it.
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
// With Size, a larger copy of the selected square is another size.
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
// With Appearance, another fill on the selected square leaves the others out.
s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the others have another fill now");
s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap();
// Reflected, the selected kite keeps its size but is no longer like its copy.
let lone = kite(&mut s, 0.0, 500.0, 1.0);
kite(&mut s, 200.0, 500.0, 1.0);
sel(&mut s, &[lone]);
assert_eq!(shown(&s).0.len(), 1);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "a reflected copy is not like it");
}
#[test]
fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 3);
s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [key]);
assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out");
}
#[test]
fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
rect(&mut s, 1100.0, 100.0, 10.0, 10.0);
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out");
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now");
}
#[test]
fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap();
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert!(highlights(&s).is_empty(), "the other instance is on the canvas");
// The symbol's art drawn 400 pt to the left: the other instance lies on the artboard.
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
let art = std::sync::Arc::make_mut(&mut d.symbols[0].art);
art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default());
st.revision += 1;
assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now");
}
#[test]
fn a_symbol_instance_put_in_perspective_has_another_size() {
use crate::cmd::globaledit::highlights;
let mut s = session();
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1);
let size = |s: &Session| bounds(s, key).size();
let was = size(&s);
s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap();
sel(&mut s, &[key]);
assert_ne!(size(&s), was, "the projection changes the instance's size");
assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had");
}
#[test]
fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap();
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1);
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art");
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1, "the whole instance again");
}
#[test]
fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
let mut s = session();
let group = |s: &mut Session, ids: &[NodeId]| {
sel(s, ids);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
};
// A group of two squares inside an outer group with a third square, and a copy of both: the
// copy's inner group is like the selected inner group.
let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)];
let inner = group(&mut s, &a);
let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let outer = group(&mut s, &[inner, third]);
let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)];
let inner_copy = group(&mut s, &b);
let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0);
group(&mut s, &[inner_copy, third_copy]);
sel(&mut s, &[inner]);
let first = highlights(&s);
assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one");
assert!(!first.is_empty());
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = walked();
assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first));
assert_eq!(walked(), before, "the outer group changed with the selected group only");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same");
assert!(walked() > before);
}
#[test]
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
let mut s = session();
+18
View File
@@ -253,6 +253,24 @@ fn transform_each_with_copy_of_50000_objects_takes_few_tree_walks() {
undo_gives_back(&mut s, &before);
}
/// A move of 10,000 selected objects walks the tree once for the paint order and the top-level
/// objects, once for Transform Patterns and the edit, and once for the selection's check after the
/// edit. It reads each object's compound path at the object's place, so the only lookups by id are
/// the range check's, one per object.
#[test]
fn moving_10000_selected_objects_walks_the_tree_three_times() {
let n = 10_000;
let mut s = session(n, square);
let ids = layer(&s, 0);
let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups());
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
let (walks, lookups) = (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups);
assert_eq!(walks, 3, "walked the tree {walks} times");
assert!(lookups <= n as u64, "{lookups} lookups by id for {n} objects");
assert_eq!(bounds(&s, ids[n - 1]), square_at(n - 1) + vectorcraft_geom::Vec2::new(3.0, 0.0));
assert!(selected(&s, &ids));
}
#[test]
fn offset_path_of_50000_objects_takes_few_tree_walks() {
let s = session(50_000, square);
+127
View File
@@ -0,0 +1,127 @@
//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far
//! it went, and only when every object the selection shows is the one before it, moved that far.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_geom::Vec2;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn doc(s: &Session) -> Arc<Document> {
s.doc().unwrap().doc.clone()
}
/// The move [`DocState::moved`] names, when it took `from` to the document now.
fn moved_from(s: &Session, from: &Arc<Document>) -> Option<Vec2> {
let st = s.doc().unwrap();
let m = st.moved.as_ref()?;
(m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by)
}
// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the
// document the drag began with.
#[test]
fn a_move_of_whole_objects_names_the_documents_and_the_distance() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a, b]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap();
assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move");
let before = doc(&s);
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge");
let start = doc(&s);
s.begin_interaction("Move").unwrap();
for dx in [3.0, 7.5] {
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap();
assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}");
}
}
// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move
// of part of what the selection shows name no move.
#[test]
fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a, b]);
let cases = [
("object.move", json!({"dx": 12, "dy": 0, "copy": true})),
("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})),
("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})),
("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})),
("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})),
];
for (cmd, p) in cases {
select(&mut s, &[a, b]);
let before = doc(&s);
s.execute(cmd, &p).unwrap();
assert_eq!(moved_from(&s, &before), None, "{cmd} {p}");
}
}
// The key object is shown too: a move that leaves it where it was names no move.
#[test]
fn a_key_object_left_where_it_was_names_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
select(&mut s, &[a]);
s.active_mut().unwrap().selection.key = Some(b);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None);
}
// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel
// grid snaps after the edit: neither is the object before the move moved by its distance.
#[test]
fn objects_that_snap_to_the_pixel_grid_name_no_move() {
let mut s = session();
let a = rect(&mut s, 20.0);
select(&mut s, &[a]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let before = doc(&s);
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path");
let mut s = session();
let art = rect(&mut s, 20.0);
let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap();
select(&mut s, &[id_of(&made)]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid");
}
// A member of a blend moved on its own changes the blend's spine.
#[test]
fn a_member_of_a_blend_names_no_move() {
let mut s = session();
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0));
s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap();
select(&mut s, &[a]);
let before = doc(&s);
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
assert_eq!(moved_from(&s, &before), None);
}
+62
View File
@@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
}
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
/// visible bounds.
#[test]
fn control_bounds_hold_the_handles_of_a_curve() {
let (mut s, _, _) = doc();
s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, c = p[0], r = p[1];\
function h(b) { return b[1] - b[3]; }\
vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\
vc.log(String(r.controlBounds) === String(r.visibleBounds));",
);
let heights = out[0].as_array().unwrap();
let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap());
// The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve.
assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}");
assert_eq!(heights[2], json!(true), "{out:?}");
assert_eq!(out[1], json!(true), "{out:?}");
}
#[test]
fn convert_coordinate_pair_is_inverse_and_y_up() {
let mut s = Session::new();
@@ -500,6 +521,7 @@ fn assigning_the_reported_opacity_changes_nothing() {
assert_eq!(out, vec![json!(33.3333)]);
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
// A value close to the reported one but not equal to it is still applied.
s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap();
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
@@ -560,6 +582,14 @@ fn selection_assignment_is_atomic_across_invalid_items() {
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
assert!(e.contains("Cannot select PathItem"), "{e}");
assert!(s.active().unwrap().selection.objects.is_empty());
// With the valid item first and the error caught, the run sees the selection unchanged.
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\
catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);",
);
assert_eq!(out, vec![json!(true), json!(0)]);
assert!(s.active().unwrap().selection.objects.is_empty());
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
let out = log(
&mut s,
@@ -2116,6 +2146,35 @@ fn prototype_changes_cannot_forge_a_page_item() {
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None);
}
#[test]
fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
let (mut s, _, _) = doc();
assert_eq!(s.tool_id(), "selection");
// A tool's id, its label and a name in the form scripts pass all choose it; the last one counts.
assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]);
assert_eq!(s.tool_id(), "pen");
log(&mut s, "app.selectTool('Rectangle Tool');");
assert_eq!(s.tool_id(), "rectangle");
log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');");
assert_eq!(s.tool_id(), "directSelection");
log(&mut s, "app.selectTool('Adobe Select Tool');");
assert_eq!(s.tool_id(), "selection");
// An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool.
assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\""));
assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named"));
let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }");
assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]);
assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop"));
let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }");
assert_eq!(out, vec![json!("TypeError")]);
assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long"));
assert_eq!(s.tool_id(), "selection");
// With no document open the tool is chosen too.
let mut empty = Session::new();
log(&mut empty, "app.selectTool('Adobe Freehand Tool');");
assert_eq!(empty.tool_id(), "pencil");
}
#[test]
fn unsupported_members_say_so() {
let (mut s, _, _) = doc();
@@ -2340,6 +2399,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
vc.log(m);",
);
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
// A name the collection inherits is not looked up as an object's name when it is assigned.
let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);");
assert_eq!(out, vec![json!(1)]);
}
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
+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);
}
+18
View File
@@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() {
assert!(holds(&[][..], &[]));
}
#[cfg(unix)]
#[test]
fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() {
use crate::store::{NOT_PLAIN, read_capped_plain};
let root = fresh_dir("plain-read");
let target = root.join("target.bin");
std::fs::write(&target, b"outside").unwrap();
let link = root.join("profile.vectorcraft");
std::os::unix::fs::symlink(&target, &link).unwrap();
assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string()));
let folder = root.join("folder");
std::fs::create_dir(&folder).unwrap();
assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string()));
assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec()));
assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec()));
assert!(read_capped_plain(&target, 6).is_err());
}
#[test]
fn a_saved_preset_replaces_an_oversized_file_in_its_place() {
let root = fresh_dir("oversized-put");
+52
View File
@@ -698,3 +698,55 @@ fn a_parametric_shape_kind_and_its_values_set_together() {
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
}
}
/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved
/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`.
/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and
/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept.
#[test]
fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() {
let mut s = session();
select(&mut s, "shapeBuilder");
assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session");
select(&mut s, "selection");
assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version");
let load = |version: Option<u32>, saved: &Value| {
let mut prefs = Prefs::default().to_json();
prefs["toolSettings"] = json!({ "shapeBuilder": saved });
let fields = prefs.as_object_mut().unwrap();
match version {
Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)),
None => fields.remove("toolSettingsVersion"),
};
let mut next = session();
next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap());
next
};
for (version, saved, want) in [
(None, json!({"highlightFill": false}), "swatches"),
(None, json!({"pickColorFrom": "artwork"}), "swatches"),
(None, json!({"pickColorFrom": "swatches"}), "swatches"),
(Some(1), json!({"pickColorFrom": "artwork"}), "artwork"),
(Some(1), json!({"pickColorFrom": "swatches"}), "swatches"),
(Some(1), json!({"highlightFill": false}), "swatches"),
] {
let mut next = load(version, &saved);
assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}");
select(&mut next, "shapeBuilder");
assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}");
select(&mut next, "selection");
assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}");
}
// Artwork picked after the update, or in a session that started without saved settings, is
// kept at the next launch.
for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] {
select(&mut next, "shapeBuilder");
next.set_tool_option("pickColorFrom", &json!("artwork"));
select(&mut next, "selection");
let saved_text = serde_json::to_string(&next.prefs).unwrap();
let mut later = session();
later.apply_prefs(serde_json::from_str(&saved_text).unwrap());
select(&mut later, "shapeBuilder");
assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}");
}
}
+1
View File
@@ -581,6 +581,7 @@ impl Session {
}
}
}
prefs.mark_tool_settings_current();
}
/// Keep the active tool's persistent options for the next time it, or a tool sharing them, is
@@ -96,8 +96,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= textFonts toString \
typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
),
("DocumentPreset.", "prototype"),
(
+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);
}
+20
View File
@@ -966,6 +966,26 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
);
}
#[test]
fn an_unavailable_member_hides_the_member_its_parent_class_has() {
let mut r = realm(1_000_000);
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass {
name: name.into(),
parent: parent.map(Into::into),
members: vec![("size".to_string(), member)],
info: Vec::new(),
index: None,
construct: None,
};
let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))];
let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))];
r.define_host_classes(classes, objects).unwrap();
r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap();
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
}
#[test]
fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() {
let mut r = realm(1_000_000);
+1 -1
View File
@@ -514,7 +514,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"text_wrap",
"Text wrap",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). A type object in `ids` below another of them is the text to wrap, not a wrap object. A `warning` says when no area type lies below them. `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.",
obj(
json!({
"ids": {"type": "array", "items": {"type": "integer"}},
+1 -1
View File
@@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
),
(
"ui.colorGuideOptions",
+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]
+1 -1
View File
@@ -208,7 +208,7 @@ features! {
ScriptuiDrawing "scriptui.drawing" Dialogs,
ScriptuiPalette "scriptui.palette" HostOnly,
ScriptuiWindow "scriptui.window" Dialogs,
SelectTool "selectTool" HostOnly,
SelectTool "selectTool" Dom,
Socket "socket" HostOnly,
UnitValue "unitValue" Language,
Xml "xml" Language,
+1 -1
View File
@@ -2011,7 +2011,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() {
fn application_methods_are_features_not_members() {
let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n");
assert!(r.members.is_empty(), "{:?}", r.members);
assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]);
assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]);
}
#[test]
-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
+4 -3
View File
@@ -66,11 +66,12 @@ pub struct ShapeBuilderOptions {
/// region as if an invisible edge closed it. When it is off, the path cuts the regions it crosses
/// as a line does.
pub open_filled_as_closed: bool,
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`; off: `"artwork"`): a merge
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`, on; off: `"artwork"`): a merge
/// fills the new shape with the current fill, and the Left and Right arrow keys step the current
/// fill through the document's color swatches. With Artwork, the shape takes the look of the
/// object where the drag starts, else of the one where it ends, else of the front-most selected
/// object.
/// object. A saved `pickColorFrom` is kept, except that preferences saved by an earlier version
/// read a saved Artwork as Color Swatches once; preferences without one take Color Swatches.
pub swatches: bool,
/// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill
/// and the swatches before and after it show as chips above the pointer while no drag is on.
@@ -105,7 +106,7 @@ impl Default for ShapeBuilderOptions {
fn default() -> Self {
Self {
open_filled_as_closed: true,
swatches: false,
swatches: true,
cursor_swatch_preview: false,
straight_line: false,
highlight_fill: true,
+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.",
+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]
+17 -1
View File
@@ -139,6 +139,8 @@ impl VectorcraftApp {
spelling: Default::default(),
text_nodes: Default::default(),
momentary: None,
hand: None,
zoom_tool: None,
selection_box: None,
selection_bounds: None,
selection_marks: None,
@@ -379,7 +381,12 @@ impl VectorcraftApp {
}
/// A window's raw input, before egui and the keys read it (the host's `raw_input_hook`).
pub fn raw_input(&self, ctx: &egui::Context, raw: &mut egui::RawInput) {
pub fn raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// AppKit consumes the key-down and winit can already have queued its key-up.
// Poll before the runtime orders the press and release in this frame's input.
if let Some(menu) = self.services.native_menu.as_mut() {
menu.poll(ctx);
}
crate::type_editing::keep_layout_text(self, ctx, raw);
}
@@ -716,7 +723,13 @@ impl VectorcraftApp {
export_progress::show(self, ui);
// After every window this pass may open, and before the palette's field takes the keyboard.
panel_docking::close_overlays_for_modal(self, &ctx);
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
dialogs::host::pump(self, &ctx);
// The canvas has already painted. A dialog can apply or roll back its preview
// on the final input frame, with no further mouse movement to wake the window.
if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document {
ctx.request_repaint();
}
prefs_dialog::show(self, ui);
crate::shortcut_editor::show(self, ui);
credits::open_taken_link(self);
@@ -823,6 +836,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
root.escape_leaves_fields = true;
// A held key repeats its command (Cmd+= keeps zooming in).
root.shortcuts_repeat = true;
// The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the
// pointer.
root.pointer_scoped_field_wheel = true;
root
}
+2 -1
View File
@@ -129,11 +129,12 @@ impl VectorcraftApp {
/// document without artboards they get neither.
fn add_active_artboard(&self, id: &str, params: &mut Value) {
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
let clipboard_command = paste || matches!(id, "edit.copy" | "edit.cut");
if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch")
&& params.get("artboard").is_none()
&& !(paste && params.get("artboards").is_some())
&& self.view().is_some()
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste)
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !clipboard_command)
&& let Some(p) = params.as_object_mut()
{
let picked = panels::artboards::picked(self, n);
+3
View File
@@ -81,6 +81,9 @@ pub struct CanvasCache {
/// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between
/// passes; the tool adapter takes it out for its call and puts it back.
pub momentary: Option<craft::ui::canvas::Momentary>,
pub hand: Option<craft::ui::canvas::HandTool>,
/// The selected Zoom tool keeps its press and drag rectangle between canvas passes.
pub zoom_tool: Option<craft::ui::canvas::ZoomTool>,
/// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and
/// Measure Type by Glyph Bounds).
pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option<vectorcraft_doc::OrientedBox>)>,
+17 -9
View File
@@ -278,8 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
pressed
}
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the
/// picture last.
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the
/// display-only widgets over it, the picture last.
fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body {
let live = kind == BodyKind::Live;
let presenting = app.ui.screen_mode == 3;
@@ -299,11 +299,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
crate::dialogs::simplify_slider::show(app, ui, &space.view);
}
guides::show(app, ui, space, win, kind);
widgets::show_hollow_corners(app, ui, space, kind);
// The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this
// frame's pointer event, from the document as the event leaves it.
// The hollow Live Corners, the selection's marks, and the bounding box, Live Corners and shape widgets paint here
// in that order, under the 3D handles and the bars. All of them are display only and are drawn after the tool host
// has taken this frame's pointer event, from the document as the event leaves it.
let hollow = PaintSlot::reserve(ui.painter());
let marks = PaintSlot::reserve(ui.painter());
widgets::show(app, ui, space, win, kind);
let shown_widgets = PaintSlot::reserve(ui.painter());
if !presenting && !revolve_editing(app) {
crate::panels::three_d::handles::show(app, ui, space);
}
@@ -339,14 +340,21 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
crate::type_editing::show(app, ui);
}
}
let after = PaintSlot::reserve(ui.painter());
selection::show(app, ui, space, win, kind);
marks.extend(ui.ctx(), after.take_after(ui.ctx()));
paint_into(ui, hollow, |ui| widgets::show_hollow_corners(app, ui, space, kind));
paint_into(ui, marks, |ui| selection::show(app, ui, space, win, kind));
paint_into(ui, shown_widgets, |ui| widgets::show(app, ui, space, win, kind));
drops::show(app, ui, win, kind);
raster::picture(app, ui, space, win, kind);
out
}
/// Runs `draw` now and moves the shapes it paints on `ui`'s layer to `slot`, their place in the paint order.
fn paint_into(ui: &mut Ui, slot: PaintSlot, draw: impl FnOnce(&mut Ui)) {
let after = PaintSlot::reserve(ui.painter());
draw(ui);
slot.extend(ui.ctx(), after.take_after(ui.ctx()));
}
/// The keys held now, as the engine's tools read them, with `space` set while Space is down.
pub(crate) fn held_mods(ctx: &egui::Context) -> vectorcraft_tools::Mods {
let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space)));
+2 -2
View File
@@ -31,7 +31,7 @@ pub(super) fn checker_of(setup: &vectorcraft_doc::DocSetup) -> Checker {
}
/// The page frames of document `st` seen through `view`: one per artboard, named "01 - name" with the
/// Artboard tool or several boards, filled with its paper or the transparency grid (nothing in Outline).
/// Artboard tool or several boards, filled with its paper or the transparency grid (white in Outline).
/// Empty while the artboards are hidden.
pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, view: &View, outline: bool) -> Vec<PageFrame> {
if !shows_artboards(app) {
@@ -51,7 +51,7 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi
frame = frame.name(format!("{:02} - {}", i + 1, ab.name));
}
if outline {
frame
frame.fill(DataColor::new(Color32::WHITE))
} else if grid {
frame.checker(checker_of(setup))
} else {
+2 -2
View File
@@ -47,13 +47,13 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() {
}
#[test]
fn outline_has_a_white_canvas_line_edges_and_no_paper() {
fn outline_has_white_artboards_on_a_white_canvas_with_line_edges() {
let _view = crate::testing::DefaultProofView::new();
let app = app_with(2);
let st = app.session.active().unwrap();
assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE)));
assert_eq!(border(true), PageBorder::Line);
assert!(frames_of(&app, true).iter().all(|f| f.fill.is_none()));
assert!(frames_of(&app, true).iter().all(|f| f.fill == Some(PageFill::Color(DataColor::new(Color32::WHITE)))));
assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Default);
assert_eq!(border(false), PageBorder::DropShadow);
assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()));
+22 -1
View File
@@ -35,7 +35,8 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
let options = super::selection::path_options(&app.session.prefs);
let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app);
let lists = [extra, overlays];
for (i, o) in extra.iter().chain(overlays).enumerate() {
// Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none.
for (i, o) in extra.iter().chain(overlays).enumerate().filter(|(_, o)| is_control(o)) {
ui.push_id(("tool-control", i), |ui| show_control(ui, rect, o));
}
for (i, list) in lists.into_iter().enumerate() {
@@ -48,6 +49,26 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
});
}
/// Whether `o` is shown as a framework control of its own ([`show_control`]) rather than painted by [`ToolMarks`].
fn is_control(o: &Overlay) -> bool {
match o {
Overlay::Marquee(_) | Overlay::SelectionMarquee { .. } | Overlay::SharedPath { .. } | Overlay::Outlines { .. } | Overlay::Distance { .. } => {
true
}
Overlay::Path { .. }
| Overlay::Line { .. }
| Overlay::Anchor { .. }
| Overlay::CurvePoint { .. }
| Overlay::Handle { .. }
| Overlay::Label { .. }
| Overlay::Measure { .. }
| Overlay::Highlight { .. }
| Overlay::Swatch { .. }
| Overlay::GridLine { .. }
| Overlay::HoverText { .. } => false,
}
}
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
match o {
+85 -10
View File
@@ -5,6 +5,7 @@
use std::collections::HashMap;
use std::collections::hash_map::{DefaultHasher, Entry};
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Weak};
use craft::behavior::Input;
use craft::behavior::Metrics;
@@ -18,9 +19,9 @@ use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline};
use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _};
use craft::ui::style::{ComponentStyle, DataColor, StyleCx};
use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{Document, NodeId, NodeKind};
use vectorcraft_engine::{DocState, Prefs, ViewInfo};
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point};
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point, Vec2};
use vectorcraft_tools::Mods;
use super::cursor::ViewKey;
@@ -632,9 +633,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect);
}
let key = marks_key(app, st, tool, tool_points);
let view = view_key(app, st, tool, tool_points);
let marks = match app.canvas.selection_marks.take() {
Some(kept) if kept.key == key => kept,
_ => SelectionMarks::build(app, st, tool, tool_points, key),
Some(kept) if kept.view == view && kept.selection == st.selection => {
kept.follow(st, key).unwrap_or_else(|| SelectionMarks::build(app, st, tool, tool_points, (key, view)))
}
_ => SelectionMarks::build(app, st, tool, tool_points, (key, view)),
};
for o in &marks.outlines {
let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision);
@@ -663,29 +668,99 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
}
/// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with
/// nothing changed walks no selected object.
/// nothing changed walks no selected object. They are also kept while the document and the selection stay the same
/// under another revision, and moved with the selection when a move ([`vectorcraft_engine::Moved`]) took the document
/// they show to the one now.
pub(crate) struct SelectionMarks {
key: u64,
/// [`view_key`] of the state they were made for.
view: u64,
/// The selection they show.
selection: vectorcraft_doc::Selection,
/// The document they show.
doc: Weak<Document>,
/// A document they show moved by a distance: the one they were built for and no distance, or the document the
/// last move they followed started from and its distance. Each step of a drag starts from the document the drag
/// began with ([`SelectionMarks::follow`]).
from: (Weak<Document>, Vec2),
outlines: Vec<Outlined>,
anchors: Anchors,
dots: Dots,
}
impl SelectionMarks {
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self {
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, (key, view): (u64, u64)) -> Self {
#[cfg(test)]
tests::MARKS_BUILT.with(|built| built.set(built.get() + 1));
Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) }
let doc = Arc::downgrade(&st.doc);
Self {
key,
view,
selection: st.selection.clone(),
from: (doc.clone(), Vec2::ZERO),
doc,
outlines: outlines(app, st),
anchors: anchors(app, st, tool, tool_points),
dots: dots(app, st),
}
}
/// The marks of `st`, whose [`marks_key`] is `key`, from these marks of the same selection and view: these marks
/// when `st` shows the same document, these marks moved by `st`'s move when it took the document they show, or the
/// document of [`SelectionMarks::from`], to the one `st` shows, else `None`.
fn follow(mut self, st: &DocState, key: u64) -> Option<Self> {
let now = Arc::as_ptr(&st.doc);
if self.doc.as_ptr() != now {
let moved = st.moved.as_ref().filter(|m| m.to.as_ptr() == now && m.selection == st.selection)?;
let by = if moved.from.ptr_eq(&self.doc) {
moved.by
} else if moved.from.ptr_eq(&self.from.0) {
moved.by - self.from.1
} else {
return None;
};
self.translate(by);
self.from = (moved.from.clone(), moved.by);
self.doc = moved.to.clone();
}
self.key = key;
Some(self)
}
/// Moves every mark by `by`.
fn translate(&mut self, by: Vec2) {
let shift = vectorcraft_geom::Affine::translate(by);
for o in &mut self.outlines {
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array());
}
for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
knot.anchor += by;
knot.in_ctrl += by;
knot.out_ctrl += by;
}
let dots = &mut self.dots;
for (at, _) in dots.origins.iter_mut().chain(&mut dots.centers).chain(&mut dots.key_anchor) {
*at += by;
}
}
}
/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the
/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the
/// Selection & Anchor Display preferences.
/// What the selection's marks are built from: the document and its selection (its uid and revision), and what
/// [`view_key`] hashes.
fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
let mut h = DefaultHasher::new();
(st.revision, view_key(app, st, tool, tool_points)).hash(&mut h);
h.finish()
}
/// What the selection's marks are built from besides the document's content and the selection: the document (its
/// uid), the parts the view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points,
/// and the Selection & Anchor Display preferences.
fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
let mut h = DefaultHasher::new();
let hides = ViewHides::of(app);
(st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
(st.uid, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
let prefs = &app.session.prefs;
(prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h);
h.finish()
@@ -918,3 +918,75 @@ fn the_canvas_builds_the_selection_marks_once_per_change() {
app.select_tool("directSelection");
assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once");
}
/// Every point of the outlines, the anchors and their handles, and the dots, in order.
fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec<Point> {
let mut out = vec![];
for path in outlines.iter().flat_map(|o| o.paths.iter().chain(&o.key)) {
for el in path.elements() {
match *el {
PathEl::MoveTo(a) | PathEl::LineTo(a) => out.push(a),
PathEl::QuadTo(a, b) => out.extend([a, b]),
PathEl::CurveTo(a, b, c) => out.extend([a, b, c]),
PathEl::ClosePath => {}
}
}
}
for knot in anchors.paths.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) {
out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]);
}
out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at));
out
}
/// Whether the marks the canvas keeps are, to rounding, the ones the builders give for the state now.
fn kept_marks_are_current(app: &VectorcraftApp) -> bool {
let kept = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
let st = app.session.active().unwrap();
let now = points_of(&outlines(app, st), &anchors(app, st, app.session.tool_id(), false), &dots(app, st));
let was = points_of(&kept.outlines, &kept.anchors, &kept.dots);
now.len() == was.len() && now.iter().zip(&was).all(|(a, b)| (*a - *b).hypot() < 1e-9)
}
// Whole-app frames keep the selection's marks through a new revision of the same document and selection, and move
// them with a move of the selection instead of building them: a move command, each step of a drag, and the drag's end
// build nothing and keep the marks of the state now. A scale and an undo still build them once.
#[test]
fn a_move_of_the_selection_moves_its_marks_without_building_them() {
let (mut app, _) = scene();
let ctx = crate::testing::ui_context();
let frames = |app: &mut VectorcraftApp, n: usize| {
let before = MARKS_BUILT.with(std::cell::Cell::get);
for _ in 0..n {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0));
crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() });
}
MARKS_BUILT.with(std::cell::Cell::get) - before
};
frames(&mut app, 3);
let layer = app.session.active().unwrap().doc.layers[0].id;
let revision = app.session.active().unwrap().revision;
app.run("layer.setCurrent", json!({"id": layer.0})).unwrap();
assert_ne!(app.session.active().unwrap().revision, revision, "a new revision");
assert_eq!(frames(&mut app, 3), 0, "a new revision of the same document and selection");
app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap();
assert_eq!(frames(&mut app, 3), 0, "a move command");
assert!(kept_marks_are_current(&app), "after a move command");
app.session.begin_interaction("Move").unwrap();
for dx in [3.0, 7.5, -2.0] {
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 4], "copy": false})).unwrap();
assert_eq!(frames(&mut app, 2), 0, "a drag's step by {dx}");
assert!(kept_marks_are_current(&app), "after a drag's step by {dx}");
}
app.session.commit_interaction().unwrap();
assert_eq!(frames(&mut app, 2), 0, "the drag's end");
assert!(kept_marks_are_current(&app), "after the drag");
app.run("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})).unwrap();
assert_eq!(frames(&mut app, 3), 1, "a scale");
assert!(kept_marks_are_current(&app), "after a scale");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(frames(&mut app, 3), 1, "an undo");
assert!(kept_marks_are_current(&app), "after an undo");
}
+103
View File
@@ -303,7 +303,22 @@ fn press(at: Pos2, pressed: bool) -> egui::Event {
/// object has after that frame's event, and none at the corner it had before it.
#[test]
fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
selection_drag_marks_follow(drag_app());
}
/// With Show Bounding Box While Moving and Drawing on, a Selection tool drag draws the bounding box and its handles in
/// the frame the pointer moves: at the corner the object has after that frame's event, and none at the corner it had
/// before it.
#[test]
fn a_selection_drag_draws_its_bounding_box_in_the_frame_the_pointer_moves() {
let mut app = drag_app();
app.session.prefs.bounding_box_while_moving_and_drawing = true;
selection_drag_marks_follow(app);
}
/// Drags a selected rectangle with the Selection tool in six frames and checks each frame that moved it: a mark at
/// its corner after the frame's event, none at its corner before.
fn selection_drag_marks_follow(mut app: VectorcraftApp) {
let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
@@ -411,6 +426,23 @@ fn a_click_activates_its_artboard_and_paste_in_place_goes_onto_it() {
assert_eq!((b.x0, b.y0), (boards[2].x0 + 10.0, boards[2].y0 + 15.0));
}
/// Copy uses the active board as its origin even when selected art lies on a different board.
#[test]
fn copy_and_paste_use_the_active_source_and_destination_artboards() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let origin = Point::new(boards[1].x0 + 10.0, boards[1].y0 + 15.0);
app.run("shape.rectangle", json!({"x": origin.x, "y": origin.y, "width": 20, "height": 20})).unwrap();
app.views[0].artboard = 0;
app.run("edit.copy", json!({})).unwrap();
app.views[0].artboard = 2;
let pasted = app.run("edit.pasteInPlace", json!({})).unwrap();
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
let bounds = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap();
assert_eq!(bounds.origin(), origin + (boards[2].origin() - boards[0].origin()));
}
/// A Shift-click with the Selection tool on an empty spot inside an artboard makes it the active
/// one and keeps the selection, and Align to Artboard then aligns the objects to it unless the
/// call names another artboard.
@@ -865,6 +897,58 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() {
assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it");
}
/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its
/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the
/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts
/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new
/// app, at most 20 times, until the other catalogs held still through it.
#[test]
fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
let fonts = vectorcraft_text::FontDb::global();
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
let catalogs = || {
(
crate::menus::plugin_revision(),
fonts.generation(),
fonts.installed_fonts_ready(),
crate::scripts_menu::revision(),
crate::dialogs::proof_setup::saved_revision(),
)
};
let run = || {
let (mut app, ctx, xf) = rectangle_tool();
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0)));
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
for _ in 0..2 {
app_step(&mut app, &ctx, vec![]);
}
let none = egui::Modifiers::NONE;
let mut steps = vec![vec![primary(from, true, none)]];
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
steps.push(vec![primary(to, false, none)]);
steps.extend([vec![], vec![], vec![]]);
let mut rebuilt = vec![];
for events in steps {
let before = app.menus.rebuilds;
app_step(&mut app, &ctx, events);
rebuilt.push(app.menus.rebuilds - before);
}
(app, rebuilt)
};
let (app, rebuilt) = (0..20)
.find_map(|_| {
let before = catalogs();
let out = run();
(catalogs() == before).then_some(out)
})
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle");
assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle");
}
/// #6369: only the selection box remains over the temporary halftone, and the original
/// selection's outlines come back when Preview is turned off or the dialog is cancelled.
#[test]
@@ -4859,6 +4943,25 @@ fn a_flip_during_a_press_waits_for_the_release() {
assert_eq!(app.session.tool_id(), "eraser", "the frame after the release");
}
/// A selected Hand tracks its drag in the framework, outside the document tool's grab.
#[test]
fn turning_the_pen_during_a_hand_drag_waits_for_release() {
let (mut app, stylus, ctx) = pen_app();
app.select_tool("hand");
let at = app.canvas_view().unwrap().rect.center();
let to = at + egui::vec2(30.0, 20.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
stylus.set(tip(0.5));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]);
stylus.set(eraser_end(0.5));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]);
assert_eq!(app.session.tool_id(), "hand");
frame(&mut app, &ctx, vec![button(to, false)]);
assert_eq!(app.session.tool_id(), "hand");
frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.tool_id(), "eraser");
}
/// #764: a tool chosen while the eraser end stands in (the toolbar and shortcuts call
/// `select_tool`; menus and MCP run `tool.select`) stays when the tip comes back.
#[test]
@@ -127,13 +127,69 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() {
let (mut app, ctx, _) = zoomed_in("hand");
let rect = app.canvas_view().unwrap().rect;
let start = rect.center();
let before = center(&app);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
let edge = pos2(rect.right() - 4.0, start.y);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
let c0 = center(&app);
assert!(c0.x < before.x, "dragging the selected Hand right must pan the view");
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
assert_eq!(center(&app), c0);
frame(&mut app, &ctx, vec![button(edge, false)]);
}
#[test]
fn a_freehand_stroke_at_the_edge_keeps_the_artwork_stationary() {
let (mut app, ctx, original) = zoomed_in("pencil");
let rect = app.canvas_view().unwrap().rect;
let start = rect.center() - vec2(120.0, 60.0);
let edge = pos2(rect.right() - 2.0, start.y + 40.0);
let initial = center(&app);
let nodes = |app: &VectorcraftApp| {
let mut count = 0;
app.session.active().unwrap().doc.walk(|_| count += 1);
count
};
let before = nodes(&app);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(15.0, 25.0))]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
for _ in 0..5 {
frame(&mut app, &ctx, vec![]);
assert_eq!(center(&app), initial);
}
frame(&mut app, &ctx, vec![button(edge, false)]);
assert!(nodes(&app) > before, "the pencil drew a new path");
assert!(app.session.active().unwrap().doc.node(original).is_some());
}
#[test]
fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() {
let (mut app, ctx, _) = zoomed_in("zoom");
app.session.prefs.animated_zoom = false;
let rect = app.canvas_view().unwrap().rect;
let position = rect.center();
let zoom = |app: &VectorcraftApp| app.view().unwrap().zoom;
let initial = zoom(&app);
for pressed in [true, false] {
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(position), button(position, pressed)]);
}
let enlarged = zoom(&app);
assert!(enlarged > initial, "click should zoom in: {initial} -> {enlarged}");
let modifiers = egui::Modifiers::ALT;
for pressed in [true, false] {
let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers };
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(modifiers), event]);
}
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
let reduced = zoom(&app);
assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}");
let start = position - vec2(90.0, 65.0);
let end = position + vec2(80.0, 55.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
frame(&mut app, &ctx, vec![button(end, false)]);
assert!(zoom(&app) > reduced, "the marquee should fit its region to the view");
}
+27 -1
View File
@@ -590,7 +590,9 @@ impl CanvasTool for SessionTool<'_> {
}
fn autoscrolls(&self) -> bool {
!self.carrying.get() && !self.view_only()
// Sampled freehand tools trace the pointer on the artwork. Scrolling
// under a held pen would extend the stroke without another sample.
!self.carrying.get() && !self.view_only() && !self.app().session.tool_wants_samples()
}
fn view_only(&self) -> bool {
@@ -629,6 +631,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
// the release, and a pointer over another window for the pointer to come in.
if ui.ctx().current_pass_index() == 0
&& app.canvas.grab.is_none()
&& !ToolHost::in_gesture(ui.ctx(), pass.id)
&& ui.input(|i| i.pointer.has_pointer())
&& crate::stylus::sync_eraser_tool(app)
{
@@ -650,7 +653,30 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
let mut picked = ToolHostResponse::default();
let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) {
picked
} else if matches!(app.session.tool_id(), "hand" | "zoom") && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() {
let options = crate::app::view::navigation(&app.session.prefs);
let response = if app.session.tool_id() == "zoom" {
app.canvas.hand = None;
let mut zoom = app.canvas.zoom_tool.take().unwrap_or_else(|| craft::ui::canvas::ZoomTool::new(options));
zoom.options = options;
let response = host_run(app, ui, pass, &mut zoom);
app.canvas.zoom_tool = Some(zoom);
response
} else {
app.canvas.zoom_tool = None;
let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options));
hand.options = options;
let response = host_run(app, ui, pass, &mut hand);
app.canvas.hand = Some(hand);
response
};
if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) {
crate::shortcuts::note_tool_use(app);
}
response
} else {
app.canvas.hand = None;
app.canvas.zoom_tool = None;
let mut tool = SessionTool::new(app, view_info, ui);
let response = host_run_session(&mut tool, ui, pass);
drop(tool);
+3 -1
View File
@@ -89,6 +89,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
Cursor::DirectAnchorSelected => tool("cursor-direct-anchor-selected", TIP, None),
Cursor::ReshapeSegment => tool("cursor-reshape-segment", TIP, None),
Cursor::GroupSelection => badged(CursorBadge::Add),
Cursor::SelectionMove => badged(CursorBadge::Move),
Cursor::SelectionCopy => badged(CursorBadge::Copy),
Cursor::Move => system(CursorIcon::Move),
Cursor::Crosshair => PaintedCursor::Crosshair.into(),
@@ -195,7 +196,7 @@ pub(crate) fn request_busy(app: &crate::VectorcraftApp, ctx: &egui::Context) {
/// Every cursor with a look: its own, or the one it borrows.
#[cfg(test)]
const GLYPHS: [Cursor; 99] = [
const GLYPHS: [Cursor; 100] = [
Cursor::Hand,
Cursor::HandGrab,
Cursor::ZoomIn,
@@ -207,6 +208,7 @@ const GLYPHS: [Cursor; 99] = [
Cursor::ReshapeSegment,
Cursor::GroupSelection,
Cursor::SelectionCopy,
Cursor::SelectionMove,
Cursor::Move,
Cursor::Crosshair,
Cursor::ResizeH,
+1
View File
@@ -148,6 +148,7 @@ pub mod slices;
pub mod smart_punctuation;
pub(crate) mod smooth_slider;
pub mod spot_colors;
pub mod step_repeat;
pub mod svg_filter;
pub(crate) mod svg_options;
pub mod swatch_conflict;
+5
View File
@@ -350,9 +350,14 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
// Free Distort's Reset puts the corners back on the box, wherever they were when it opened.
let reset_to = (id == super::free_distort::FREE_DISTORT)
.then(|| form::fields_of(&rows, &Map::from_iter([("corners".to_string(), json!(super::free_distort::IDENTITY))])));
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, "effect", fields, move |f| {
let rows = effect_params(&cx, f);
let dialog = ParamDialog::new("effect", title.clone(), rows).values(Bind::bound(f)).previews(true);
let dialog = match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
};
let dialog = match &reset_to {
Some(target) => dialog.reset_to(target.clone()),
None => dialog,
+60 -9
View File
@@ -114,11 +114,19 @@ pub(super) fn render_preview(
app: &mut VectorcraftApp,
ctx: &egui::Context,
doc: &vectorcraft_engine::doc::Document,
) -> Option<Arc<egui::ColorImage>> {
render_page_preview(&mut app.canvas.renderer, ctx.pixels_per_point(), doc)
}
fn render_page_preview(
renderer: &mut vectorcraft_render::Renderer,
pixels_per_point: f32,
doc: &vectorcraft_engine::doc::Document,
) -> Option<Arc<egui::ColorImage>> {
let region = doc.artboards.first()?.rect;
let px = PREVIEW_PX * ctx.pixels_per_point() as f64;
let px = PREVIEW_PX * pixels_per_point as f64;
let scale = px / region.width().max(region.height()).max(1.0);
let img = app.canvas.renderer.render_region(doc, region, scale, true);
let img = renderer.render_region(doc, region, scale, true);
Some(Arc::new(crate::canvas::color_image(&img)))
}
@@ -286,6 +294,8 @@ pub(super) struct ImportPdfDialog {
/// The preview shown for a (page, crop, text) revision; `None` for a page that could not be read, which is
/// not asked for again.
preview: Option<(Revision, Option<Arc<egui::ColorImage>>)>,
/// One preview at a time. Page changes coalesce while the worker finishes.
pending_preview: Option<(Revision, std::sync::mpsc::Receiver<Option<Arc<egui::ColorImage>>>)>,
/// Why the last password did not open the file.
password_error: Option<String>,
/// The OK the pump has not answered.
@@ -294,7 +304,7 @@ pub(super) struct ImportPdfDialog {
impl ImportPdfDialog {
fn new(s: State) -> Self {
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, password_error: None, held: HeldAnswer::new() }
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, pending_preview: None, password_error: None, held: HeldAnswer::new() }
}
/// The preview to render next: the revision of the shown page, crop and text, when the stored one differs.
@@ -700,7 +710,14 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
if s.links_on() {
p["linkPages"] = json!(true);
}
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
if crate::opening::available()
&& let Some(path) = s.path.as_deref()
{
crate::opening::start_with(app, path, s.file.bytes.clone(), p);
Ok(())
} else {
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
}
};
// Asked only for the password, the dialog showed no Text choice to keep; the choice for a `.ai`
// or `.ait` file is not kept for PDFs.
@@ -711,10 +728,10 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
}
/// The preview of the page and boxes `s` shows; `None` for a page that can't be read.
fn preview_image(app: &mut VectorcraftApp, ctx: &egui::Context, s: &State) -> Option<Arc<egui::ColorImage>> {
fn preview_image(renderer: &mut vectorcraft_render::Renderer, pixels_per_point: f32, s: &State) -> Option<Arc<egui::ColorImage>> {
let opts = fileio::LoadOptions { crop: s.crop, password: s.password(), text_as: s.preview_text_as(), ..Default::default() };
let (doc, _) = fileio::page_document(&s.file.bytes, s.page().saturating_sub(1), &opts).ok()?;
render_preview(app, ctx, &doc)
render_page_preview(renderer, pixels_per_point, &doc)
}
/// The host pump: judges the OK the dialog holds (opening or placing the file; a refusal keeps the dialog open with
@@ -730,10 +747,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
dialog.answer_ok(answer);
}
});
return;
}
let wanted = dialogs.with(|host| host.get::<ImportPdfDialog>().and_then(|d| Some((d.wanted_preview()?, d.s.clone()))));
if let Some((revision, s)) = wanted {
let image = preview_image(app, ctx, &s);
let wanted = dialogs.with(|host| {
let dialog = host.get_mut::<ImportPdfDialog>()?;
if let Some((revision, pending)) = &dialog.pending_preview {
let image = match pending.try_recv() {
Ok(image) => image,
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
};
if dialog.wanted_preview() == Some(*revision) {
dialog.set_preview(*revision, image);
}
dialog.pending_preview = None;
}
Some((dialog.wanted_preview()?, dialog.s.clone()))
});
let Some((revision, state)) = wanted else { return };
let pixels_per_point = ctx.pixels_per_point();
if crate::opening::available() {
let (sender, pending) = std::sync::mpsc::channel();
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
dialog.pending_preview = Some((revision, pending));
}
});
let wake = ctx.clone();
let scope = vectorcraft_engine::file_access::ScopeHandle::capture();
app.jobs().spawn(
"vectorcraft-pdf-preview",
Box::new(move || {
let image = scope.run(|| preview_image(&mut vectorcraft_render::Renderer::new(), pixels_per_point, &state));
let _ = sender.send(image);
wake.request_repaint();
}),
);
} else {
let image = preview_image(&mut app.canvas.renderer, pixels_per_point, &state);
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
dialog.set_preview(revision, image);
+6 -1
View File
@@ -4,7 +4,8 @@ use super::path_ops::PathOp;
use super::simplify_slider::StripKind;
use super::{
blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, transform, transform_each, width_point,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, transform_each,
width_point,
};
use crate::VectorcraftApp;
@@ -15,6 +16,8 @@ pub(crate) struct ObjectDialogs {
pub transform: Option<transform::Open>,
/// The open Transform Each dialog's preview record.
pub each: Option<transform_each::Open>,
/// The open Step and Repeat dialog's preview record.
pub step: Option<step_repeat::Open>,
/// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records.
pub path: Vec<path_ops::Open>,
/// The open Split Into Grid dialog's record.
@@ -46,6 +49,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
sync(app);
transform::pump(app, ctx);
transform_each::pump(app, ctx);
step_repeat::pump(app, ctx);
path_ops::pump(app, ctx);
shapes::pump(app, ctx);
flare_options::pump(app, ctx);
@@ -73,6 +77,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> bool {
}
match id {
"object.transformEach" => transform_each::open(app),
step_repeat::CMD => step_repeat::open(app),
"path.average" => path_ops::open(app, PathOp::Average),
"path.averageJoin" => path_ops::open(app, PathOp::AverageJoin),
"object.path.offsetPath" => path_ops::open(app, PathOp::OffsetPath),
+1 -1
View File
@@ -631,7 +631,7 @@ pub(super) mod tests {
tool: "shapeBuilder",
opens_on: vec![
("openFilledAsClosed", json!(true)),
("pickColorFrom", json!("artwork")),
("pickColorFrom", json!("swatches")),
("cursorSwatchPreview", json!(false)),
("selection", json!("freeform")),
("highlightFill", json!(true)),
+14 -4
View File
@@ -42,7 +42,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use craft::menu::Node;
use craft::ui::contract::Show as _;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
use craft::ui::display::{Shade, Text};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog};
@@ -548,7 +548,13 @@ pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
/// language when it changes while the dialog is open; the field values stay as they are.
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
fn build(
key: &'static str,
m: Manifest,
all: Arc<[Param]>,
look: Look,
canvas: Option<egui::Id>,
) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
let rows_in = std::sync::Mutex::new((lang(), all));
move |fields| {
let all = {
@@ -564,7 +570,10 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
}
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews).values(Bind::bound(fields));
if let Some(canvas) = canvas.filter(|_| look.previews) {
dialog = dialog.canvas(canvas);
}
if let Some(ok) = look.ok {
dialog = dialog.ok_label(ok.into());
}
@@ -592,7 +601,8 @@ fn open_hosted(
close_open(app);
let all: Arc<[Param]> = form::plugin_params(&m, &values).into();
let fields = form::fields_of(&all, &values);
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string());
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look, canvas)).instance(instance.to_string());
let id = dialogs.with(|host| host.open(dialog));
Ok((id, all))
}
@@ -110,7 +110,7 @@ impl RearrangeValues {
}
/// The length unit a document unit shows as.
fn length_kind(unit: Unit) -> UnitKind {
pub(super) fn length_kind(unit: Unit) -> UnitKind {
match unit {
Unit::Picas => UnitKind::Picas,
Unit::Inches => UnitKind::Inches,
+16 -6
View File
@@ -114,22 +114,32 @@ fn rows() -> Vec<(&'static str, &'static str, &'static str, Value)> {
#[test]
fn a_3d_row_sets_its_param_previews_and_applies_in_one_step() {
// One window serves every row: Cancel, and OK followed by Undo, leave the drawing as the dialog found it, and each
// row opens the dialog again over it.
let mut shown: Option<ThreeD> = None;
for (effect, page, key, value) in rows() {
let name = format!("{effect}.{key}");
for confirm in [false, true] {
let mut h = drawn(SQUARE, effect);
let before = source(&h);
let p = json!({"effect": effect, "item": null});
let h = match shown.as_mut() {
Some(h) => {
reopen(h, p);
h
}
None => shown.insert(opened(app_with(SQUARE), p)),
};
let before = source(h);
h.set("__page", json!(page));
h.set(key, value.clone());
assert!(same(&stored(&h, effect)[key], &value), "{name}: the preview follows the row");
assert!(same(&stored(h, effect)[key], &value), "{name}: the preview follows the row");
if confirm {
h.ok();
assert!(same(&stored(&h, effect)[key], &value), "{name}: OK keeps it");
undo(&h);
assert!(same(&stored(h, effect)[key], &value), "{name}: OK keeps it");
undo(h);
} else {
h.cancel();
}
assert_eq!(doc(&h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" });
assert_eq!(doc(h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" });
}
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Object → Step and Repeat: copies of the selection on a grid or filling a sheet, with the gaps
//! between the cut paths, every other column or row turned by 180° (`object.stepAndRepeat`),
//! previewed live on the canvas.
//!
//! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the
//! artboard), `rotate` (`none`, `columns` or `rows`), `cutId` (an object of the selection, or
//! empty for the selection itself).
use craft::ui::contract::Bind;
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
use serde_json::{Map, Value, json};
use super::host::{HeldOptions, open_held_with};
use super::preview::LivePreview;
use crate::VectorcraftApp;
pub(crate) const CMD: &str = "object.stepAndRepeat";
pub(crate) struct Open {
pub id: DialogId,
pub preview: LivePreview,
}
fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> {
let mut out = vec![];
for id in selected {
if let Some(n) = doc.node(*id) {
n.walk(&mut |c| out.push((c.id.0, c.display_name())));
}
}
out
}
fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> {
let mut out = vec![(String::new(), Label::from(tl!("Selection")))];
if let Some(st) = app.session.active() {
out.extend(cut_ids(&st.doc, &st.selection.objects).into_iter().map(|(id, name)| (id.to_string(), Label::from(name))));
}
out
}
fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec<Param> {
let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths);
vec![
Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false),
Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false),
len("gapX", tl!("Horizontal Gap")),
len("gapY", tl!("Vertical Gap")),
Param::new("cutId", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))),
Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)),
len("margin", tl!("Margin")).enabled_when("fill", true),
Param::new(
"rotate",
tl!("Rotate 180°"),
ParamKind::choice(
vec![
("none".into(), Label::from(tl!("None"))),
("columns".into(), Label::from(tl!("Every Other Column"))),
("rows".into(), Label::from(tl!("Every Other Row"))),
],
Some("none".into()),
),
),
]
}
pub fn fields() -> DialogFields {
DialogFields::from_pairs([
("rows", FieldValue::Int(2)),
("columns", FieldValue::Int(2)),
("gapX", FieldValue::Number(12.0)),
("gapY", FieldValue::Number(12.0)),
("margin", FieldValue::Number(0.0)),
("fill", FieldValue::Bool(false)),
("cutId", FieldValue::Text(String::new())),
("rotate", FieldValue::Text("none".into())),
])
}
fn count(f: &DialogFields, key: &str) -> u64 {
f.int(key).or_else(|| f.number(key).map(|n| n as i64)).unwrap_or(1).max(1) as u64
}
fn params(f: &DialogFields) -> Value {
let mut p = Map::new();
p.insert("rows".into(), json!(count(f, "rows")));
p.insert("columns".into(), json!(count(f, "columns")));
for k in ["gapX", "gapY", "margin"] {
p.insert(k.into(), json!(f.number(k).unwrap_or(0.0)));
}
p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false)));
p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none")));
if let Some(id) = f.text("cutId").and_then(|t| t.parse::<u64>().ok()) {
p.insert("cutId".into(), json!(id));
}
Value::Object(p)
}
pub(crate) fn open(app: &mut VectorcraftApp) {
let _ = try_open(app);
}
fn try_open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0);
let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points);
let cuts = cut_options(app);
let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| {
ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields))
});
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?;
let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields));
if done.is_err() {
app.object_dialogs.step = Some(open);
}
done.map(|_| ())
};
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.object_dialogs.step.take() {
open.preview.cancel(app);
}
});
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.object_dialogs.step = Some(Open { id, preview: LivePreview::default() });
Ok(Value::Null)
}
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.object_dialogs.step.take() else { return };
let shown =
app.dialogs().and_then(|host| host.with(|h| h.get_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((on, p)) = shown {
let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p);
}
app.object_dialogs.step = Some(open);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cut_path_is_sent_only_when_one_is_chosen() {
let mut f = fields();
assert!(params(&f).get("cutId").is_none());
f.set("cutId", FieldValue::Text("42".into()));
assert_eq!(params(&f)["cutId"], json!(42));
}
#[test]
fn cut_choices_reach_objects_nested_in_groups() {
let mut s = vectorcraft_engine::Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [inner, c]})).unwrap();
let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let ids: Vec<u64> = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect();
assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i)));
}
}
@@ -117,6 +117,20 @@ fn pdf_page_footer_ok_opens_the_chosen_range() {
assert_eq!(artboard_widths(h.state()), [200.0, 300.0]);
}
#[test]
fn confirming_a_desktop_pdf_import_queues_the_read_and_closes_the_dialog() {
crate::opening::tests::with_threads(|| {
let mut app = app();
io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("three.pdf".into())).unwrap();
set(&mut app, "allPages", json!(false));
set(&mut app, "range", json!("2-3"));
confirm(&mut app).unwrap();
assert!(!is_open(&app));
assert_eq!(app.opening.pending.len(), 1);
assert_eq!(app.opening.pending[0].path, "three.pdf");
});
}
#[test]
fn opening_a_multi_page_pdf_asks_for_the_pages() {
let mut app = app();
+5
View File
@@ -150,11 +150,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) {
let document = app.session.active().map(|doc| (doc.uid, doc.reverts));
let rows = rows(app, kind, &opening);
let fields = fields_of(&rows, &opening);
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| {
if kind == Kind::Move {
link_distance_and_angle(f);
}
let dialog = ParamDialog::new(kind.command(), kind.title(), rows.clone()).previews(true).values(Bind::bound(f));
let dialog = match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
};
if kind == Kind::Move { dialog.remember(MOVE_KEY) } else { dialog }
});
// A dialog this one replaces leaves its preview behind otherwise.
+24
View File
@@ -1,6 +1,8 @@
//! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or
//! flyout panel.
use craft::ui::contract::{Props as _, Scroll, ShowContainer as _};
use craft::ui::layout_components::Stack;
use egui::Ui;
use crate::state::DockTab;
@@ -13,6 +15,28 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
Some(DockTab::Properties) => panels::properties::show(app, ui),
Some(DockTab::Layers) => panels::layers::show(app, ui),
Some(DockTab::Libraries) => panels::libraries(app, ui),
None if matches!(
id,
"align"
| "attributes"
| "blend"
| "character"
| "color"
| "magicWand"
| "openType"
| "paragraph"
| "pathfinder"
| "patternOptions"
| "stroke"
| "tabs"
| "transform"
| "transparency"
) =>
{
// These panels lay out forms. Collection panels own their scrolling viewport
// and reserve their own footer outside it.
Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id));
}
None => panels::show_icon_panel(app, ui, id),
}
}
+1 -1
View File
@@ -114,7 +114,7 @@ pub(crate) fn family_picker<'a>(
.filters(filters)
.sets(sets)
.scripts(&FontScript::ALL)
.filter_layout(FilterLayout::Chips)
.filter_layout(FilterLayout::Toolbar)
}
/// What one pass of a picker reads of the app, for a host that has no `app` while it draws (a dialog).
+2
View File
@@ -92,6 +92,8 @@ pub use run::{check_params, run_ui_command};
pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
#[cfg(test)]
use slots::RECENT_FONT_IDS;
#[cfg(test)]
pub(crate) use state::WHY_OFF_ASKED;
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
pub(crate) use submenus::PATH_EFFECTS;
+21 -7
View File
@@ -1,7 +1,9 @@
use craft::keymap::{Chord, CommandRef};
use super::context::context_items;
use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label};
use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut_in, spelling_item_label, unlock_item_label};
use super::slots::{recent_readable, recent_slot};
use super::state::{shortcut_of, shown_state};
use super::state::{command_shortcuts, shown_state};
use super::tree::{Listed, menu_tree_named};
use super::{Node, Serialize, Value, VectorcraftApp, unbound};
@@ -32,8 +34,9 @@ pub struct MenuEntry {
/// Flattened menu for `ui.menu.list`.
pub fn menu_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
let mut out = vec![];
let chord = command_shortcuts(app);
for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english, &Listed::of(app)) {
flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out);
flatten(app, &chord, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out);
}
out
}
@@ -41,7 +44,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
/// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus).
pub fn context_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
let mut out = vec![];
flatten(app, vec![], vec![], &context_items(app), &mut out);
flatten(app, &command_shortcuts(app), vec![], vec![], &context_items(app), &mut out);
out
}
@@ -166,7 +169,15 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec<InsertableI
out
}
pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String>, nodes: &[Node], out: &mut Vec<MenuEntry>) {
/// `nodes` flattened into `out`, each item's shortcut looked up in `chord` ([`command_shortcuts`]).
pub(super) fn flatten(
app: &VectorcraftApp,
chord: &dyn Fn(&CommandRef) -> Option<Chord>,
path: Vec<String>,
shown: Vec<String>,
nodes: &[Node],
out: &mut Vec<MenuEntry>,
) {
for node in nodes {
match node {
Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry {
@@ -197,7 +208,10 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String
command: Some(id.to_string()),
params: p.clone(),
enabled,
shortcut: item_shortcut(app, id, p).or_else(|| shortcut_of(app, id)).map(|c| c.to_string()).unwrap_or_default(),
shortcut: item_shortcut_in(chord, id, p)
.or_else(|| chord(&crate::keymap::command_of(id)))
.map(|c| c.to_string())
.unwrap_or_default(),
shown_path: shown.clone(),
})
}
@@ -209,7 +223,7 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String
let mut s = shown.clone();
let own = super::labels::holds_plugin_commands(children) || crate::scripts_menu::is_folder(children);
s.push(if own { label.clone() } else { crate::i18n::tr(crate::i18n::current(), label).to_string() });
flatten(app, p, s, children, out);
flatten(app, chord, p, s, children, out);
}
_ => {}
}
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more