mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 22:19:00 +00:00
Merge main into feat/scripts-print-printer
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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
-193
File diff suppressed because it is too large
Load Diff
+52
-57
@@ -4,56 +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"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[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" }
|
||||
@@ -89,7 +90,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
peniko = "0.6"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
@@ -159,10 +159,8 @@ egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
webbrowser = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -196,25 +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" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { 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" }
|
||||
|
||||
@@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -5,6 +5,10 @@ dist = "../../dist/web"
|
||||
public_url = "./"
|
||||
filehash = true
|
||||
|
||||
[tools]
|
||||
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
|
||||
wasm_opt = "version_133"
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8766
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
+15
-11
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::ControlFlow;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -403,6 +404,8 @@ thread_local! {
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`has_own_effects`] read an object's effects on this thread.
|
||||
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
@@ -527,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
@@ -568,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -1188,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
|
||||
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
n.try_walk(&mut |c| {
|
||||
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
})
|
||||
.is_break()
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
#[cfg(test)]
|
||||
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
|
||||
@@ -3652,6 +3652,48 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
|
||||
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
|
||||
/// once.
|
||||
#[test]
|
||||
fn hovers_past_plain_paths_read_each_paths_effects_once() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let paths = 100;
|
||||
for i in 0..paths {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
|
||||
let read = reads() - before;
|
||||
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
|
||||
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
|
||||
/// object found with one: the members after it are not read.
|
||||
#[test]
|
||||
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
|
||||
set_clip_region(moved_clip_region);
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let members: Vec<_> = (0..100)
|
||||
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
|
||||
.collect();
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance.effects.push(test_move());
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(has_effects(&mask));
|
||||
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
|
||||
let symbols = d.symbol_boxes();
|
||||
let before = reads();
|
||||
assert!(draws_effects(&symbols, &mask));
|
||||
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
|
||||
}
|
||||
|
||||
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
|
||||
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
|
||||
#[test]
|
||||
|
||||
@@ -308,16 +308,8 @@ fn resolve_kids(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
|
||||
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
|
||||
pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
|
||||
use crate::text::TextObject;
|
||||
|
||||
mod attributes;
|
||||
mod changed;
|
||||
mod clip;
|
||||
mod extras;
|
||||
mod ids;
|
||||
@@ -25,6 +26,9 @@ mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Arc, Node, NodeId};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
|
||||
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
|
||||
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
|
||||
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
|
||||
/// node is new). A node that is the same node as the one at its position in `before` is skipped
|
||||
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
|
||||
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
|
||||
after.iter().enumerate().filter_map(move |(i, a)| {
|
||||
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
Some((i, a, b))
|
||||
})
|
||||
}
|
||||
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
|
||||
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
|
||||
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
|
||||
/// the same nodes in the same places are passed over by their pointers.
|
||||
#[test]
|
||||
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
|
||||
let mut after = before.clone();
|
||||
let mut edited = (*after[500]).clone();
|
||||
edited.name = Some("edited".into());
|
||||
after[500] = Arc::new(edited);
|
||||
after.push(leaf(5000));
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(0));
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
|
||||
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
|
||||
}
|
||||
|
||||
/// A node that moved to another place in the list is paired with itself by its id and left out
|
||||
/// when it is the same node; a changed node that moved is paired with its old node, and a node
|
||||
/// that is gone from the list gives nothing.
|
||||
#[test]
|
||||
fn changed_nodes_pairs_moved_nodes_by_id() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
|
||||
let mut edited = (*before[0]).clone();
|
||||
edited.locked = true;
|
||||
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
|
||||
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
|
||||
assert_eq!(changed_nodes(&[], &after).count(), 3);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
|
||||
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
@@ -89,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.match",
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupOverlapping",
|
||||
"Group Overlapping Objects",
|
||||
@@ -177,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
|
||||
s.note_journal("scaleStrokes", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -277,7 +295,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
@@ -290,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -341,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
@@ -359,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
|
||||
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
|
||||
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
|
||||
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
|
||||
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
|
||||
Some("bottom") => roots.first().copied(),
|
||||
Some(_) => roots.last().copied(),
|
||||
None => key.or_else(|| roots.last().copied()),
|
||||
};
|
||||
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
|
||||
}
|
||||
|
||||
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
|
||||
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
|
||||
let paths = d.index_paths(targets.iter().copied().chain([source]));
|
||||
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
|
||||
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
|
||||
}
|
||||
|
||||
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.match";
|
||||
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
|
||||
let rotate = switch_or(p, "rotate", false, C)?;
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let source = match_source(s, p, &roots, C)?;
|
||||
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
|
||||
let (w, h) = if size == "none" {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let sb = box_of(s, source)?;
|
||||
(sb.rect.width(), sb.rect.height())
|
||||
};
|
||||
let wanted = match size {
|
||||
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
|
||||
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
|
||||
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
|
||||
"width" => Some(json!({ "width": w, "proportional": true })),
|
||||
"height" => Some(json!({ "height": h, "proportional": true })),
|
||||
"both" => Some(json!({ "width": w, "height": h })),
|
||||
_ => None,
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
if wanted.is_some() {
|
||||
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let mut xf = Affine::IDENTITY;
|
||||
if let Some(q) = &wanted {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
xfs.retain(|(_, xf)| !still(xf));
|
||||
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
|
||||
let (mut placed, mut left) = (vec![], vec![]);
|
||||
if restack {
|
||||
let d = &s.doc()?.doc;
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
|
||||
let is_clip =
|
||||
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
|
||||
if targets.iter().any(is_clip) {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
|
||||
left = crate::cmd::intertwine::groups_of(d, &targets);
|
||||
}
|
||||
let count = json!({ "source": source.0, "count": targets.len() });
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -505,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
|
||||
@@ -343,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
|
||||
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
|
||||
/// (100, 100) and `c` 10 × 30 at (200, 0).
|
||||
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_gives_the_others_the_key_objects_size() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r, json!({"source": b.0, "count": 2}));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// About each center; the key object stays.
|
||||
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
|
||||
// The width, with the height in proportion, about the top-left corner.
|
||||
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
|
||||
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
// No key object: the frontmost, c.
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(a.0));
|
||||
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// "top" names the frontmost even while a key object is set.
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_to_the_sources_angle() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
|
||||
let at = o.center();
|
||||
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
|
||||
}
|
||||
// Turned back to the angle of an unturned source.
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, d]);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
|
||||
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
for size in ["width", "height", "both"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
|
||||
assert_eq!(r, json!({"source": source.0, "count": 1}));
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[target]).is_none());
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
|
||||
if angle == 0 {
|
||||
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_puts_the_others_directly_above_the_source() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[d, a, c]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "already above it: no step");
|
||||
// An object in another layer goes into the source's.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b, e]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b, e]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_makes_no_step_when_everything_matches() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(steps(&s), n, "the same size and angle: no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_about_their_reference_point() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
|
||||
// Each top-left corner stays where it was.
|
||||
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
|
||||
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_scales_strokes_as_asked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
|
||||
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
|
||||
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
|
||||
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
|
||||
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
|
||||
select(&mut s, &[art, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[mask, x]);
|
||||
s.execute("select.key", &json!({"id": x.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
|
||||
// Its height can still take the source's.
|
||||
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[line]).unwrap().rect;
|
||||
let wanted = s.transform_box(&[b]).unwrap().rect;
|
||||
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
|
||||
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, c]);
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
|
||||
let e = d.node(a).unwrap().extras();
|
||||
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_needs_no_bounds_on_the_source() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
select(&mut s, &[b, g]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, b]);
|
||||
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
|
||||
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[c, d]);
|
||||
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't be intertwined"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, _, _) = three(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.match",
|
||||
&[
|
||||
json!({}),
|
||||
json!({"size": "none"}),
|
||||
json!({"size": "area"}),
|
||||
json!({"size": 1}),
|
||||
json!({"rotate": 1}),
|
||||
json!({"stacking": "yes"}),
|
||||
json!({"size": "both", "reference": 9}),
|
||||
json!({"size": "both", "reference": 1.5}),
|
||||
json!({"size": "both", "source": "left"}),
|
||||
json!({"size": "both", "scaleStrokes": "no"}),
|
||||
json!({"size": "both", "patterns": 0}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no key object"), "{e}");
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -389,6 +777,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.swap",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
|
||||
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
|
||||
}
|
||||
let Some(children) = n.children() else { return false };
|
||||
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
};
|
||||
stale_in(doc, c, b)
|
||||
})
|
||||
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
|
||||
}
|
||||
|
||||
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
@@ -54,8 +54,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
let mut roots = members(&s.doc()?.doc, &checked_ids_or_selection(s, p, C)?);
|
||||
// An id given twice, or a circle given with its group, is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
@@ -140,6 +140,22 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The objects `ids` names, with each group among them (a clipping group excepted) as the objects
|
||||
/// inside it, at any depth.
|
||||
fn members(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)),
|
||||
_ => out.push(n.id),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for n in ids.iter().filter_map(|&id| d.node(id)) {
|
||||
visit(n, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
|
||||
@@ -354,3 +354,60 @@ fn locked_and_hidden_circles_are_not_bridged() {
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
}
|
||||
|
||||
fn group(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
NodeId(s.execute("object.group", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn children(s: &Session, id: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_group_of_circles_bridges_the_circles_inside_it() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 160.0, 100.0, 20.0);
|
||||
let g = group(&mut s, &[a, b]);
|
||||
select(&mut s, &[g]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0), "two circles, joined in the upper one's place");
|
||||
assert_eq!(top_level(&s), [g]);
|
||||
assert_eq!(children(&s, g), [b], "the outline stays in the group");
|
||||
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(children(&s, g), [a, b]);
|
||||
|
||||
// A group inside a group, given with one of its own circles, and a loose circle: three circles, so the reach
|
||||
// applies.
|
||||
let c = circle(&mut s, 300.0, 100.0, 20.0);
|
||||
let outer = group(&mut s, &[g]);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [outer.0, a.0, c.0], "reach": 30})).unwrap();
|
||||
assert_eq!(r["ids"], json!([b.0]), "the grouped circles are joined");
|
||||
assert_eq!(r["alone"], json!([c.0]), "the far circle is out of reach");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_group_with_other_objects_or_a_clipping_group_is_refused() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 160.0, 100.0, 20.0);
|
||||
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let g = group(&mut s, &[a, b, square]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(err(&mut s, json!({"ids": [g.0]})).contains("select two or more circles to bridge"));
|
||||
assert_eq!(children(&s, g), [a, b, square]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 160.0, 100.0, 20.0);
|
||||
let mask = circle(&mut s, 130.0, 100.0, 80.0);
|
||||
select(&mut s, &[a, b, mask]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = top_level(&s);
|
||||
assert!(err(&mut s, json!({"ids": [clip.0]})).contains("select two or more circles to bridge"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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 }))
|
||||
|
||||
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
"{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
"{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
@@ -967,7 +967,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
|
||||
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let roots = roots_placed(&st.doc, ids, &paths, |_, _| false);
|
||||
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
|
||||
roots
|
||||
})
|
||||
@@ -1015,7 +1016,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
|
||||
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
Ok(roots_placed(&st.doc, ids, &paths, |_, _| true))
|
||||
}
|
||||
|
||||
/// The objects of `objects` that are in `doc`, in paint order as
|
||||
/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One
|
||||
/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after
|
||||
/// `in_paint_order` walks the tree twice).
|
||||
fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec<NodeId>, HashMap<NodeId, Vec<usize>>) {
|
||||
let paths = doc.index_paths(objects.iter().copied());
|
||||
let mut ids: Vec<NodeId> = objects.iter().copied().filter(|id| paths.contains_key(id)).collect();
|
||||
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
(ids, paths)
|
||||
}
|
||||
|
||||
/// [`selected_roots`] for the selected objects inside the isolated object `root`
|
||||
@@ -1027,8 +1040,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root))
|
||||
}
|
||||
|
||||
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
|
||||
@@ -1042,6 +1056,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
|
||||
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
|
||||
let paths = doc.index_paths(ids.iter().copied());
|
||||
roots_placed(doc, ids, &paths, keep_member)
|
||||
}
|
||||
|
||||
/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already.
|
||||
fn roots_placed(doc: &Document, ids: Vec<NodeId>, paths: &HashMap<NodeId, Vec<usize>>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
|
||||
// A compound-path member acts as its compound (compounds are one object).
|
||||
let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
|
||||
.into_iter()
|
||||
@@ -1105,7 +1124,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
|
||||
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
|
||||
})
|
||||
};
|
||||
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound));
|
||||
Ok((direct, roots))
|
||||
}
|
||||
|
||||
@@ -1163,6 +1183,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() }))
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
|
||||
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
|
||||
/// computer's when `None`).
|
||||
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
|
||||
let fonts: Vec<Value> = missing_fonts(&st.doc)
|
||||
let fonts = missing_font_rows(&st.doc);
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
if let Some(dir) = fonts_next_to_document(st, rules) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
|
||||
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
|
||||
missing_fonts(d)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
|
||||
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
|
||||
/// `rules` (this computer's when `None`).
|
||||
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
|
||||
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
|
||||
// is made absolute against the working folder when the document's path is relative. It is
|
||||
// offered when a search may start there, as far as the rules tell without listing a folder.
|
||||
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
};
|
||||
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
|
||||
}
|
||||
|
||||
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
|
||||
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
|
||||
@@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound
|
||||
/// path is read at the parent's place, without looking either object up by id.
|
||||
pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) {
|
||||
let Some((_, up)) = path.split_last() else { return };
|
||||
if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) {
|
||||
return;
|
||||
}
|
||||
if let Some(n) = d.node_mut_at(up) {
|
||||
snap_object(n, sc);
|
||||
}
|
||||
}
|
||||
|
||||
/// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added
|
||||
/// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity
|
||||
/// mask, to the pixel grid. Objects the edit did not touch are not visited.
|
||||
@@ -226,15 +238,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
@@ -423,15 +427,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
|
||||
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
|
||||
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
|
||||
out.push(a.id);
|
||||
} else if let Some(children) = a.children() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
|
||||
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
|
||||
/// (`before`: the same list before the edit), outer ones first.
|
||||
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if is_objects_on_path(a) {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
/// The colour mode an image file stores its pixels in.
|
||||
fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
|
||||
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
|
||||
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
|
||||
/// and the Properties panel ask `image.info` again after every change, each step of a drag
|
||||
/// included. A file in another format is decoded.
|
||||
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
|
||||
match craft_image_codecs::inspect_raster(bytes) {
|
||||
Ok(Some(i)) => match i.color_type {
|
||||
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
|
||||
T::Cmyk | T::CmykAlpha => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
|
||||
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(L::Gray | L::GrayA) => "Grayscale",
|
||||
Some(L::Cmyk | L::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.replace",
|
||||
@@ -408,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",
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -6,12 +6,9 @@ use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{self as b, BuilderMap};
|
||||
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
|
||||
}
|
||||
|
||||
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().shaper.is_some() {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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,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)]
|
||||
|
||||
@@ -522,7 +522,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;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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`]),
|
||||
@@ -174,7 +177,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>,
|
||||
@@ -213,6 +217,7 @@ pub(super) struct State {
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -236,6 +241,12 @@ impl State {
|
||||
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
|
||||
self.printing.take_jobs()
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -861,12 +872,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();
|
||||
@@ -1038,6 +1061,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>
|
||||
@@ -2241,9 +2327,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| {
|
||||
@@ -2257,7 +2343,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.
|
||||
@@ -2859,6 +2945,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")])),
|
||||
|
||||
@@ -2691,7 +2691,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)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
mod newdoc;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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(), ¶ms["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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() {
|
||||
assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back");
|
||||
}
|
||||
|
||||
/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale
|
||||
/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again
|
||||
/// after every step of a drag, so a decode there redid a large image's whole decode each step.
|
||||
#[test]
|
||||
fn image_color_mode_reads_the_header_without_decoding_the_pixels() {
|
||||
let raw: Vec<u8> = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale");
|
||||
// Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC.
|
||||
let mut at = 8;
|
||||
let mut idat = 0;
|
||||
while at + 12 <= png.len() {
|
||||
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
|
||||
if &png[at + 4..at + 8] == b"IDAT" {
|
||||
png[at + 8..at + 8 + len].fill(0);
|
||||
let crc = crc32fast::hash(&png[at + 4..at + 8 + len]);
|
||||
png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
|
||||
idat += 1;
|
||||
}
|
||||
at += 12 + len;
|
||||
}
|
||||
assert!(idat > 0, "the PNG has pixel data");
|
||||
assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode");
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode");
|
||||
}
|
||||
|
||||
/// The colour mode read from a file's header is the one its decoded pixels have, in every format
|
||||
/// and channel layout the codecs write.
|
||||
#[test]
|
||||
fn image_color_mode_from_the_header_matches_the_decoded_pixels() {
|
||||
use craft_image_codecs::{ChannelLayout as L, Format as F};
|
||||
let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) {
|
||||
Ok(L::Gray | L::GrayA) => "Grayscale",
|
||||
Ok(L::Cmyk | L::CmykA) => "CMYK",
|
||||
Ok(_) => "RGB",
|
||||
Err(e) => panic!("the written file decodes: {e}"),
|
||||
};
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut checked = 0;
|
||||
for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] {
|
||||
for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] {
|
||||
let n = 16 * 16 * layout.channels();
|
||||
let raw: Vec<u8> = (0..n).map(|i| (i * 13 % 256) as u8).collect();
|
||||
let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue };
|
||||
let want = decoded(&bytes);
|
||||
assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}");
|
||||
seen.insert(want);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked >= 12, "{checked} files written");
|
||||
assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CMYK", "Grayscale", "RGB"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_needs_exactly_one_selected_object() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2348,29 +2348,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
/// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that
|
||||
/// runs on the thread that made this one is not held, since nothing could let it go: it goes
|
||||
/// ahead at once and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let go = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
let test_thread = std::thread::current().id();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
if std::thread::current().id() == test_thread {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
let (open, opened) = &*g;
|
||||
let mut open = open.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while !*open {
|
||||
open = opened.wait(open).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
@@ -2381,7 +2387,9 @@ impl HeldLoad {
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let (open, opened) = &*self.go;
|
||||
*open.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
opened.notify_all();
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
@@ -2905,6 +2913,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
@@ -2918,7 +2927,6 @@ fn a_query_runs_while_the_plugins_load() {
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
@@ -2936,18 +2944,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
// A load run on this thread isn't held, so a free lock then shows nothing.
|
||||
assert!(!held.gave_up(), "the module loaded on the test's thread");
|
||||
// Other tests take the lock for a moment; the held load holding it would hold it until it is let go.
|
||||
while !crate::cmd::plugin::plugin_changes_free() {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
}
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
@@ -2975,6 +2979,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
// Canceling waits for a running load until its deadline; the second module, let go, loads
|
||||
// while the cancel runs or before it, and doesn't install either way.
|
||||
held.release();
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1002,6 +1002,10 @@ fn structured_junk() {
|
||||
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
|
||||
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
|
||||
@@ -96,7 +96,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \
|
||||
selection selection= textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
|
||||
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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"}},
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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]
|
||||
|
||||
@@ -231,7 +231,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,
|
||||
|
||||
@@ -1709,7 +1709,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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -136,7 +136,9 @@ fn neighbours(sp: &SubPath, i: usize) -> [Option<usize>; 2] {
|
||||
/// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it
|
||||
/// change. A smooth anchor takes the Curvature tool's own handles ([`smooth_handles`]: along the
|
||||
/// circle through it and its neighbours; at an end of an open path the one [`end_handle`] into the
|
||||
/// curve). The neighbours' handles on those segments, and a corner's own
|
||||
/// curve), each no longer than [`fit_to_tangent`] allows against the neighbor's handle on its
|
||||
/// segment, so a point dragged far out narrows toward it instead of swinging wide around that
|
||||
/// circle (#6192). The neighbors' handles on those segments, and a corner's own
|
||||
/// handles, keep their directions, their lengths scaling with their segment's chord, so the
|
||||
/// segments beyond don't move and a corner without handles keeps none.
|
||||
///
|
||||
@@ -163,7 +165,7 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
|
||||
match ends {
|
||||
[Some(prev), Some(next)] => {
|
||||
if let Some((h_in, h_out)) = smooth_handles(prev.p, q, next.p) {
|
||||
(m.h_in, m.h_out) = (h_in, h_out);
|
||||
(m.h_in, m.h_out) = (fit_to_tangent(q, h_in, prev.p, prev.h_out), fit_to_tangent(q, h_out, next.p, next.h_in));
|
||||
}
|
||||
}
|
||||
// An end of an open path has one segment: its handle only, and a corner like the
|
||||
@@ -179,6 +181,48 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// cos 75°: [`fit_to_tangent`] shortens a handle in full up to a turn of 150°, and less toward a
|
||||
/// half turn.
|
||||
const FADE_HALF_TURN: f64 = 0.258_819_045_102_520_8;
|
||||
|
||||
/// Handle `h` of the point `q` on its segment to `b`, whose handle there is `hb`, shortened toward
|
||||
/// the handle of the circular arc tangent to both handle lines: `2/3 · (1 − tan²(θ/4))` of `q`'s
|
||||
/// distance `r` to where the lines meet, `θ` the turn between them. A longer handle swings the
|
||||
/// segment out past `b`'s tangent line. The shortening applies in full while the lines meet at
|
||||
/// least half the chord ahead of `b` and the turn is at most 150°, and fades to none as the meeting
|
||||
/// point comes back to `b` or the turn nears a half turn, so the handle changes continuously as `q`
|
||||
/// moves. Where `b` is on the circle [`smooth_handles`]
|
||||
/// follows, the arc is the circle's and `h` is unchanged; `h` is also unchanged when `b` has no
|
||||
/// handle there or the lines are parallel.
|
||||
fn fit_to_tangent(q: Point, h: Point, b: Point, hb: Point) -> Point {
|
||||
let (d, t) = (h - q, hb - b);
|
||||
let (ld, lt) = (d.hypot(), t.hypot());
|
||||
let w = b - q;
|
||||
let chord = w.hypot();
|
||||
if !(ld > 1e-9 && lt > 1e-9 && chord > 1e-9) {
|
||||
return h;
|
||||
}
|
||||
let (d, t) = (d / ld, t / lt);
|
||||
let den = d.cross(t);
|
||||
if den.abs() <= 1e-12 {
|
||||
return h;
|
||||
}
|
||||
// q + r·d = b + s·t.
|
||||
let (r, s) = (w.cross(t) / den, w.cross(d) / den);
|
||||
// The curve leaves `b` along `t` and comes into `q` along −d.
|
||||
let cos_half = ((1.0 - t.dot(d)) / 2.0).clamp(0.0, 1.0).sqrt();
|
||||
// A circular arc under a half turn meets its tangents at least half its chord out. Toward a
|
||||
// half turn the lines meet ever further away, on one side or the other, and the shortening
|
||||
// fades out.
|
||||
let weight = (2.0 * s / chord).clamp(0.0, 1.0) * (cos_half / FADE_HALF_TURN).min(1.0);
|
||||
let tan2 = (1.0 - cos_half) / (1.0 + cos_half);
|
||||
let cap = 2.0 / 3.0 * (1.0 - tan2) * r.abs();
|
||||
if !(weight > 0.0 && cap.is_finite() && ld > cap) {
|
||||
return h;
|
||||
}
|
||||
q + d * (ld + (cap - ld) * weight)
|
||||
}
|
||||
|
||||
/// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape: the new anchor's
|
||||
/// index. On a straight segment its handles lie along it, each a third of its own part of the
|
||||
/// segment ([`curvature_smooth`]: a line is a circle's limit), so a drag bends the line evenly; a drag then moves it as a
|
||||
|
||||
@@ -139,6 +139,98 @@ fn moving_a_corner_without_handles_keeps_its_sides_straight() {
|
||||
assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0)));
|
||||
}
|
||||
|
||||
/// A circle's top point dragged far up stretches it into a shape that narrows from its sides
|
||||
/// toward the point (#6192), instead of swinging out wider than the circle first. The moved point
|
||||
/// stays smooth, and its segments meet the neighbors' unchanged tangents.
|
||||
#[test]
|
||||
fn stretching_a_circle_narrows_toward_the_dragged_point() {
|
||||
let k = 100.0 * 0.552_284_749_830_793_4;
|
||||
let circle = SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)),
|
||||
Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)),
|
||||
Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)),
|
||||
Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)),
|
||||
],
|
||||
true,
|
||||
);
|
||||
// On the circle, the neighbors' tangents match it, and the point keeps the circle's handles.
|
||||
let mut near = circle.clone();
|
||||
assert!(curvature_move(&mut near, 0, pt(0.0, -100.0)));
|
||||
for (a, b) in near.anchors.iter().zip(&circle.anchors) {
|
||||
assert!(a.h_in.distance(b.h_in) < 1e-6 && a.h_out.distance(b.h_out) < 1e-6, "{a:?} != {b:?}");
|
||||
}
|
||||
for top in [-150.0, -250.0, -400.0, -800.0] {
|
||||
let mut sp = circle.clone();
|
||||
assert!(curvature_move(&mut sp, 0, pt(0.0, top)));
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
assert!(collinear(a.h_in - a.p, a.h_out - a.p) && (a.h_in - a.p).dot(a.h_out - a.p) < 0.0);
|
||||
// Segment 0 runs from the top to the right point, segment 3 from the left point to the top.
|
||||
for (seg, side) in [(0, 1.0), (3, -1.0)] {
|
||||
let c = sp.segment(seg);
|
||||
let mut last: Option<f64> = None;
|
||||
for j in 0..=200 {
|
||||
let t = j as f64 / 200.0;
|
||||
let p = c.eval(if side > 0.0 { t } else { 1.0 - t });
|
||||
assert!(p.x.abs() <= 100.0 + 1e-9, "top {top}: segment {seg} swings out to x = {}", p.x);
|
||||
// From the top down to the side the width only grows.
|
||||
if let Some(l) = last {
|
||||
assert!(p.x.abs() >= l - 1e-9, "top {top}: segment {seg} narrows again at t = {t}");
|
||||
}
|
||||
last = Some(p.x.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The moved point's handles change continuously while it crosses a neighbor's tangent line, while
|
||||
/// the line its own handle runs along passes through the neighbor, and while the two lines turn
|
||||
/// parallel.
|
||||
#[test]
|
||||
fn a_moved_point_s_handles_change_continuously() {
|
||||
let handles = |sp: &SubPath, q: Point| -> (Vec2, Vec2) {
|
||||
let mut sp = sp.clone();
|
||||
assert!(curvature_move(&mut sp, 1, q));
|
||||
(sp.anchors[1].h_in - q, sp.anchors[1].h_out - q)
|
||||
};
|
||||
let near = |a: (Vec2, Vec2), b: (Vec2, Vec2)| (a.0 - b.0).hypot() < 0.05 && (a.1 - b.1).hypot() < 0.05;
|
||||
// The neighbor's handle points away from the moved point: its line passes through it at y = 0.
|
||||
let away = SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(pt(-100.0, 0.0)),
|
||||
Anchor::with_handles(pt(0.0, -20.0), pt(-30.0, -20.0), pt(30.0, -20.0)),
|
||||
Anchor::with_handles(pt(100.0, 0.0), pt(200.0, 10.0), pt(0.0, -10.0)),
|
||||
],
|
||||
false,
|
||||
);
|
||||
assert!(near(handles(&away, pt(0.0, -0.001)), handles(&away, pt(0.0, 0.001))));
|
||||
// The neighbor's handle runs the same way as the moved point's: their lines are parallel at x = 0.
|
||||
let parallel = SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(pt(-100.0, 0.0)),
|
||||
Anchor::with_handles(pt(0.0, -50.0), pt(-30.0, -50.0), pt(30.0, -50.0)),
|
||||
Anchor::with_handles(pt(100.0, 0.0), pt(150.0, 0.0), pt(50.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
);
|
||||
assert!(near(handles(¶llel, pt(-0.001, -50.0)), handles(¶llel, pt(0.001, -50.0))));
|
||||
// A circle's top dragged across the right point's tangent line, x = 100.
|
||||
let k = 100.0 * 0.552_284_749_830_793_4;
|
||||
let circle = SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)),
|
||||
Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)),
|
||||
Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)),
|
||||
Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)),
|
||||
],
|
||||
true,
|
||||
);
|
||||
for y in [-150.0, -300.0] {
|
||||
assert!(near(handles(&circle, pt(99.999, y)), handles(&circle, pt(100.001, y))), "y {y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_from_an_end_keeps_the_old_segments() {
|
||||
let before = wave();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and
|
||||
//! Sort Objects,
|
||||
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
|
||||
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
|
||||
@@ -25,14 +26,16 @@ const GRID: &str = "addon.arrange.grid";
|
||||
const OFFSET: &str = "addon.arrange.offset";
|
||||
const REPLACE: &str = "addon.arrange.replace";
|
||||
const SIZE: &str = "addon.arrange.size";
|
||||
const MATCH: &str = "addon.arrange.match";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 6] = [
|
||||
const DIALOGS: [(&str, &str); 7] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
(SIZE, "Set Size of Each"),
|
||||
(MATCH, "Match Objects"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
];
|
||||
@@ -63,6 +66,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
|
||||
c("Replace with Top Object…", REPLACE),
|
||||
c("Set Size of Each…", SIZE),
|
||||
c("Match Objects…", MATCH),
|
||||
cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
@@ -75,6 +79,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None
|
||||
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
|
||||
@@ -149,6 +154,20 @@ fn size_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn match_rows() -> Vec<Param> {
|
||||
let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")];
|
||||
let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")];
|
||||
vec![
|
||||
choice("source", "Match To:", &sources, "key"),
|
||||
choice("size", "Size:", &sizes, "both"),
|
||||
check("rotate", "Rotation", false),
|
||||
check("stacking", "Stacking Order", false),
|
||||
reference_param("reference", tl!("Reference Point")),
|
||||
scale_strokes().enabled_when_in("size", ["width", "height", "both"]),
|
||||
check("patterns", "Transform Patterns", false),
|
||||
]
|
||||
}
|
||||
|
||||
fn opacity_rows() -> Vec<Param> {
|
||||
vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()]
|
||||
}
|
||||
@@ -192,6 +211,10 @@ fn size_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
fn match_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&match_rows(), fields))
|
||||
}
|
||||
|
||||
fn opacity_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&opacity_rows(), fields))
|
||||
}
|
||||
@@ -205,6 +228,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
|
||||
let st = app.session.active()?;
|
||||
let strokes = app.session.prefs.scale_strokes;
|
||||
let key = st.selection.key.is_some();
|
||||
let lengths = general_lengths(app);
|
||||
let (rows, opening) = match command {
|
||||
// A square grid to start with: as many columns as the square root of the count.
|
||||
@@ -217,6 +241,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
),
|
||||
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
|
||||
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
|
||||
// The key object while the selection has one, else the top object.
|
||||
MATCH => (
|
||||
match_rows(),
|
||||
json!({
|
||||
"source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false,
|
||||
"reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles,
|
||||
}),
|
||||
),
|
||||
// A new seed each time the document has changed, so running it again varies the result.
|
||||
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
|
||||
// The random order's seed (not shown): new whenever the document has changed, so each run
|
||||
@@ -245,6 +277,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
|
||||
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
|
||||
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
|
||||
MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| {
|
||||
let chosen = fields.text("size").is_some_and(|size| size != "none")
|
||||
|| fields.bool("rotate") == Some(true)
|
||||
|| fields.bool("stacking") == Some(true);
|
||||
let source = key || fields.text("source") != Some("key");
|
||||
let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") };
|
||||
dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields))
|
||||
}),
|
||||
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
|
||||
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
|
||||
@@ -231,6 +231,59 @@ fn set_size_of_each_sets_the_sides_ticked() {
|
||||
assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0));
|
||||
}
|
||||
|
||||
fn layer_order(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_match_keyboard_edits_preview_confirm_and_cancel() {
|
||||
let (app, a, b) = app();
|
||||
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = steps(&app);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
// No key object: it opens on the top object, b, and previews its size on a.
|
||||
assert_eq!(
|
||||
host::read(&panel.app(), id, |f| (f.text("source").map(str::to_owned), f.text("size").map(str::to_owned))),
|
||||
(Some("top".into()), Some("both".into()))
|
||||
);
|
||||
assert_eq!(bounds(&panel.app(), a), vectorcraft_geom::Rect::new(-10.0, -15.0, 30.0, 25.0));
|
||||
panel.focus("Stacking Order");
|
||||
panel.key(egui::Key::Space, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.bool("stacking")), Some(true));
|
||||
assert_eq!(layer_order(&panel.app()), [b, a], "the preview puts a above b");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!((bounds(&app, a), layer_order(&app), steps(&app)), (vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0), vec![a, b], before));
|
||||
}
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), id, "size", json!("none"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "nothing to match");
|
||||
host::set(&panel.app(), id, "size", json!("width"));
|
||||
host::set(&panel.app(), id, "source", json!("key"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "the selection has no key object");
|
||||
host::set(&panel.app(), id, "source", json!("bottom"));
|
||||
panel.frame();
|
||||
assert!(panel.enabled("OK"));
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
// b takes a's width, its height in proportion, as one undo step.
|
||||
assert_eq!(bounds(&app, b), vectorcraft_geom::Rect::new(110.0, 110.0, 130.0, 130.0));
|
||||
assert_eq!(bounds(&app, a), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0));
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() {
|
||||
let (mut app, a, b) = app();
|
||||
|
||||
@@ -40,8 +40,8 @@ fn params(fields: &DialogFields) -> Value {
|
||||
/// Opens Smooth Bridge's dialog on the command's defaults.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
// The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview
|
||||
// replaces the selection with its result.
|
||||
let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true);
|
||||
// replaces the selection with its result, with a selected group counting the objects inside it.
|
||||
let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true);
|
||||
let fields = DialogFields::from_pairs([
|
||||
("radius", FieldValue::Number(RADIUS)),
|
||||
("constantGap", FieldValue::Bool(false)),
|
||||
@@ -72,6 +72,24 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the
|
||||
/// objects inside it, at any depth; an object given twice, or with its group, counts once.
|
||||
fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize {
|
||||
fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet<vectorcraft_doc::NodeId>) {
|
||||
match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)),
|
||||
_ => {
|
||||
out.insert(n.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = std::collections::BTreeSet::new();
|
||||
for n in ids.iter().filter_map(|&id| doc.node(id)) {
|
||||
visit(n, &mut out);
|
||||
}
|
||||
out.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
@@ -158,6 +176,36 @@ mod tests {
|
||||
assert_eq!(geometry(&panel.app()), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reach_counts_the_circles_inside_a_selected_group() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] {
|
||||
let mut app = bridge_app(xs);
|
||||
let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
|
||||
let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [group]})).unwrap();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len());
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len();
|
||||
assert_eq!(inside, 1, "the circles in the group became one shape");
|
||||
}
|
||||
// A group of two circles selected together with one of them: still two circles.
|
||||
let mut app = bridge_app(&[100.0, 124.0]);
|
||||
let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
|
||||
let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2);
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("Reach"), "a circle selected with its group counts once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
|
||||
@@ -134,10 +134,13 @@ impl VectorcraftApp {
|
||||
print_tiling: None,
|
||||
live_paint_gaps: None,
|
||||
find_font: None,
|
||||
missing_fonts: vec![],
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
text_nodes: Default::default(),
|
||||
momentary: None,
|
||||
hand: None,
|
||||
zoom_tool: None,
|
||||
selection_box: None,
|
||||
selection_bounds: None,
|
||||
selection_marks: None,
|
||||
@@ -378,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);
|
||||
}
|
||||
|
||||
@@ -715,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);
|
||||
@@ -822,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user