diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json
index 6427f339db..55d2a1983c 100644
--- a/.github/nightly-signing-policy.json
+++ b/.github/nightly-signing-policy.json
@@ -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",
diff --git a/.github/scripts/release-rpm-smoke.py b/.github/scripts/release-rpm-smoke.py
new file mode 100644
index 0000000000..3d70cca7c1
--- /dev/null
+++ b/.github/scripts/release-rpm-smoke.py
@@ -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('')
+ 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"))
diff --git a/.github/scripts/tests/test_release_rpm_smoke.py b/.github/scripts/tests/test_release_rpm_smoke.py
new file mode 100644
index 0000000000..9d92237534
--- /dev/null
+++ b/.github/scripts/tests/test_release_rpm_smoke.py
@@ -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()
diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml
index dd4a4a02da..4ef372c40b 100644
--- a/.github/workflows/nightly-dispatch.yml
+++ b/.github/workflows/nightly-dispatch.yml
@@ -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
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
index 0e963e43e1..c2224a81ba 100644
--- a/.github/workflows/nightly.yml
+++ b/.github/workflows/nightly.yml
@@ -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:
diff --git a/.github/workflows/release-rpm-smoke.yml b/.github/workflows/release-rpm-smoke.yml
new file mode 100644
index 0000000000..61948e0f35
--- /dev/null
+++ b/.github/workflows/release-rpm-smoke.yml
@@ -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
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 226830fc1b..ea3bf92583 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -42,6 +42,8 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: vectorcraft
app-title: VectorCraft
+ macos-runner: macos-15
+ macos-split-build: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml
index 4cd4eb6387..98e9c1d00a 100644
--- a/.github/workflows/sonarcloud.yml
+++ b/.github/workflows/sonarcloud.yml
@@ -11,7 +11,7 @@ permissions:
contents: read
concurrency:
- group: sonarcloud-${{ github.ref }}
+ group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
@@ -21,4 +21,7 @@ jobs:
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
# archive stays within hosted-runner memory (craft-common-actions#333).
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
+ with:
+ python-coverage-source: .github/scripts
+ python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py
secrets: inherit
diff --git a/Cargo.lock b/Cargo.lock
index d7b77b1065..4fce3ecad1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1816,6 +1816,14 @@ dependencies = [
"encoding_rs",
]
+[[package]]
+name = "craft-nightly"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
+dependencies = [
+ "winsafe",
+]
+
[[package]]
name = "craft-pages"
version = "0.1.0"
@@ -8515,13 +8523,14 @@ dependencies = [
[[package]]
name = "vectorcraft"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"arboard",
"block2 0.6.2",
"chrono",
"clipboard-win",
"craft",
+ "craft-nightly",
"eframe",
"egui",
"egui_extras",
@@ -8558,7 +8567,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-affinity",
"craft-image-codecs",
@@ -8569,26 +8578,26 @@ dependencies = [
[[package]]
name = "vectorcraft-apischema"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"serde_json",
]
[[package]]
name = "vectorcraft-brush"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"serde",
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
]
[[package]]
name = "vectorcraft-cad"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-dxf",
"craft-image-codecs",
@@ -8600,14 +8609,14 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-geom 0.25.0",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-cli"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -8618,7 +8627,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -8630,7 +8639,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-cms",
"craft-color-ui",
@@ -8646,7 +8655,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"chrono",
"craft-image-codecs",
@@ -8662,13 +8671,13 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"zune-jpeg",
]
[[package]]
name = "vectorcraft-effects"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-svg",
@@ -8678,8 +8687,8 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom 0.24.1",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-geom 0.25.0",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
@@ -8689,7 +8698,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"apple-native-keyring-store",
"cfb",
@@ -8738,10 +8747,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-js",
"vectorcraft-metafile",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -8761,7 +8770,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-eps",
"craft-image-codecs",
@@ -8782,9 +8791,9 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-eps",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-metafile",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -8793,7 +8802,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-gzip",
"craft-vectorcraft-format",
@@ -8805,7 +8814,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-brush",
"vectorcraft-doc",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-testkit",
]
@@ -8821,7 +8830,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -8832,7 +8841,7 @@ dependencies = [
[[package]]
name = "vectorcraft-js"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"chrono",
"craft-xml",
@@ -8843,7 +8852,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft",
"craft-image-codecs",
@@ -8855,7 +8864,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -8864,7 +8873,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-metafile",
@@ -8874,7 +8883,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-text",
]
@@ -8891,19 +8900,19 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
"proptest",
"thiserror 2.0.21",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-pdf"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"aes 0.8.4",
"chrono",
@@ -8932,7 +8941,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-pdf",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -8940,7 +8949,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugin-worker"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"js-sys",
"vectorcraft-plugins",
@@ -8950,7 +8959,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-vectorcraft-format",
@@ -8962,7 +8971,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-js",
"vectorcraft-plugins",
"wasmi",
@@ -8973,7 +8982,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-gif",
"craft-image-codecs",
@@ -8991,7 +9000,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -9004,7 +9013,7 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"proptest",
"unicode-properties",
@@ -9012,7 +9021,7 @@ dependencies = [
[[package]]
name = "vectorcraft-svg"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-docpath",
"craft-image-codecs",
@@ -9036,15 +9045,15 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-geom 0.25.0",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-testkit",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-testkit"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"fax",
@@ -9055,14 +9064,14 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-render",
"vectorcraft-svg",
]
[[package]]
name = "vectorcraft-text"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft",
"craft-fonts-build",
@@ -9080,23 +9089,23 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vello_cpu",
"write-fonts",
]
[[package]]
name = "vectorcraft-three-d"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"proptest",
- "vectorcraft-geom 0.24.1",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-geom 0.25.0",
+ "vectorcraft-pathops 0.25.0",
]
[[package]]
name = "vectorcraft-thumbnail-handler"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"png 0.18.1",
"windows",
@@ -9105,7 +9114,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"kurbo 0.13.1",
@@ -9115,15 +9124,15 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
- "vectorcraft-geom 0.24.1",
- "vectorcraft-pathops 0.24.1",
+ "vectorcraft-geom 0.25.0",
+ "vectorcraft-pathops 0.25.0",
"vectorcraft-text",
"vectorcraft-tools",
]
[[package]]
name = "vectorcraft-trace"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft-image-codecs",
"image",
@@ -9131,12 +9140,12 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
]
[[package]]
name = "vectorcraft-ui-egui"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"bytemuck",
"chrono",
@@ -9160,7 +9169,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
- "vectorcraft-geom 0.24.1",
+ "vectorcraft-geom 0.25.0",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -9175,7 +9184,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"craft",
"craft-web-api",
@@ -10404,7 +10413,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
-version = "0.24.1"
+version = "0.25.0"
dependencies = [
"serde_json",
]
@@ -10759,18 +10768,3 @@ dependencies = [
"syn 3.0.9",
"winnow",
]
-
-[[patch.unused]]
-name = "egui_demo_lib"
-version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
-
-[[patch.unused]]
-name = "egui_inspection"
-version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
-
-[[patch.unused]]
-name = "egui_system_font_provider"
-version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
diff --git a/Cargo.toml b/Cargo.toml
index 41bca3bd33..cc76d129c5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,11 +4,10 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
-version = "0.24.1"
+version = "0.25.0"
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" }
@@ -54,6 +53,8 @@ craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db
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" }
+# Nightly profile isolation, launch protocol, and security fence.
+craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
# 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"
@@ -213,8 +211,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed1817
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" }
diff --git a/ROADMAP.md b/ROADMAP.md
index c743448b07..e317f148d8 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -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.
diff --git a/apps/vectorcraft-web/Trunk.toml b/apps/vectorcraft-web/Trunk.toml
index aad9a1638f..1bb9ef3f24 100644
--- a/apps/vectorcraft-web/Trunk.toml
+++ b/apps/vectorcraft-web/Trunk.toml
@@ -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
diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml
index d17c96eaf7..3ec7da1b75 100644
--- a/apps/vectorcraft/Cargo.toml
+++ b/apps/vectorcraft/Cargo.toml
@@ -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 }
diff --git a/apps/vectorcraft/src/build_flavor.rs b/apps/vectorcraft/src/build_flavor.rs
index 9450a48972..93876b5cce 100644
--- a/apps/vectorcraft/src/build_flavor.rs
+++ b/apps/vectorcraft/src/build_flavor.rs
@@ -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)");
+ }
}
diff --git a/apps/vectorcraft/src/launch_profile.rs b/apps/vectorcraft/src/launch_profile.rs
index 12615dd81d..d986f28d71 100644
--- a/apps/vectorcraft/src/launch_profile.rs
+++ b/apps/vectorcraft/src/launch_profile.rs
@@ -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 -- [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 -- [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,
-}
-
-static PROFILE: OnceLock = 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) -> Result {
- 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) -> Result {
- 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, exe: Option<&Path>) -> Result {
- crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable)
+pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator- ) -> Result {
+ 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 {
child_args_for(current(), files)
@@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec {
#[cfg(not(target_os = "macos"))]
fn child_args_for(profile: &Profile, files: &[String]) -> Vec {
- let mut args: Vec = 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 = 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 {
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 {
- 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"]));
}
}
diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs
index 5a7d3e33ba..601cda01bb 100644
--- a/apps/vectorcraft/src/main.rs
+++ b/apps/vectorcraft/src/main.rs
@@ -384,58 +384,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> {
- // 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
- // --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 +442,11 @@ fn prepare_launch() -> Option> {
// 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 {
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
@@ -520,8 +509,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)]
diff --git a/apps/vectorcraft/src/profile_root.rs b/apps/vectorcraft/src/profile_root.rs
index 7f46e77766..d5ae707a17 100644
--- a/apps/vectorcraft/src/profile_root.rs
+++ b/apps/vectorcraft/src/profile_root.rs
@@ -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 {
- 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 {
- 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, key: &str) -> Result {
- 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, key: &str, fallback: &str) -> Result {
- 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 {
- 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 {
- 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::>()
- };
- let (a, b) = (parts(a), parts(b));
- a.starts_with(&b) || b.starts_with(&a)
-}
-
-fn installation_boundary(platform: Platform, exe: &Path) -> Result {
- 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, exe: &Path) -> Result, 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::, _>>()?;
- 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::, _>>()?;
- // 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::, _>>()?;
- 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, label: &str) -> Result {
- 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,
- exe: Option<&Path>,
- writable: impl FnOnce(&Path) -> std::io::Result<()>,
-) -> Result {
- validate_for(Platform::current()?, root, env, exe, writable)
+fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option {
+ 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,
- exe: Option<&Path>,
- writable: impl FnOnce(&Path) -> std::io::Result<()>,
-) -> Result {
- 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 {
+ 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, exe: Option<&Path>) -> Vec {
+ 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,
- 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 {
- self.env.get(key).cloned()
- }
-
- fn home(&self) -> PathBuf {
- PathBuf::from(self.get("HOME").unwrap())
- }
-
- fn check(&self, platform: Platform, root: &Path) -> Result {
- self.check_with(platform, root, |_| Ok(()))
- }
-
- fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result {
- 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());
}
}
diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs
index 249309fa87..4dba61d6b4 100644
--- a/apps/vectorcraft/src/single_instance.rs
+++ b/apps/vectorcraft/src/single_instance.rs
@@ -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));
diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs
index bb4dcbd416..2a92cfb160 100644
--- a/crates/doc/src/hit.rs
+++ b/crates/doc/src/hit.rs
@@ -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 = 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 = 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(mask: bool, f: impl FnOnce() -> T) -> T {
/// kept alone.
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option)> {
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))
}
diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs
index 2f51917dde..a678797ff5 100644
--- a/crates/doc/src/hit/tests.rs
+++ b/crates/doc/src/hit/tests.rs
@@ -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]
diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs
index b22f6cbfc7..731fba6d34 100644
--- a/crates/doc/src/inline.rs
+++ b/crates/doc/src/inline.rs
@@ -308,16 +308,8 @@ fn resolve_kids(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec,
) -> Vec<(usize, Arc)> {
- let mut by_id: Option>> = 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));
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 470b0a94c4..6a331c6b77 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -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;
diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs
index 87b9a375db..3a4b2abd03 100644
--- a/crates/doc/src/node.rs
+++ b/crates/doc/src/node.rs
@@ -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};
diff --git a/crates/doc/src/node/changed.rs b/crates/doc/src/node/changed.rs
new file mode 100644
index 0000000000..4aba12f78e
--- /dev/null
+++ b/crates/doc/src/node/changed.rs
@@ -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 = 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], after: &'a [Arc]) -> impl Iterator
- , Option<&'a Arc>)> {
+ let mut by_id: Option>> = 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))
+ })
+}
diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs
index 8d6520265a..ed2fdb08d9 100644
--- a/crates/doc/src/node/tests.rs
+++ b/crates/doc/src/node/tests.rs
@@ -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> = (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);
+}
diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs
index a25f341d1c..c1e99bb155 100644
--- a/crates/engine/src/cmd/addons/arrange.rs
+++ b/crates/engine/src/cmd/addons/arrange.rs
@@ -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 {
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 {
+ 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 {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
@@ -277,7 +295,7 @@ fn offset(s: &mut Session, p: &Value) -> Result {
fn swap(s: &mut Session, p: &Value) -> Result {
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 {
fn replace(s: &mut Session, p: &Value) -> Result {
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 {
}
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 {
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 {
+ 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 {
+ 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 = 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| {
+ 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::)>>();
+ 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 = 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 {
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)"));
diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs
index 498a927898..265ab50a6a 100644
--- a/crates/engine/src/cmd/addons/arrange/tests.rs
+++ b/crates/engine/src/cmd/addons/arrange/tests.rs
@@ -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",
diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs
index 7fdb0c5c3e..a46818befb 100644
--- a/crates/engine/src/cmd/addons/image/mask.rs
+++ b/crates/engine/src/cmd/addons/image/mask.rs
@@ -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, old: Option<&Arc>) -> 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>> = 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
diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs
index c13b256210..4cc41982df 100644
--- a/crates/engine/src/cmd/fontfiles.rs
+++ b/crates/engine/src/cmd/fontfiles.rs
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec {
/// `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 = 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 {
+ 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 {
// 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 {
diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs
index 4f498e972a..b2d6098e56 100644
--- a/crates/engine/src/cmd/globaledit.rs
+++ b/crates/engine/src/cmd/globaledit.rs
@@ -194,6 +194,51 @@ impl Options {
/// Outlines with their layer colours ([`highlights`]).
pub type Outlines = Vec<(BezPath, [u8; 3])>;
+/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
+/// allocation back until the outlines are found again.
+#[derive(Debug, Default, PartialEq)]
+pub struct Highlights {
+ /// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
+ /// it stroked for these outlines while the number stays the same.
+ pub revision: u64,
+ /// The outlines in each layer color, the colors in the order of their first outline.
+ pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
+}
+
+/// The [`Highlights::revision`] the next set of outlines takes.
+static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
+/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
+static NO_HIGHLIGHTS: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default);
+
+impl Highlights {
+ /// `outlines` grouped by color, under a new revision.
+ fn new(outlines: Outlines) -> std::sync::Arc {
+ if outlines.is_empty() {
+ return NO_HIGHLIGHTS.clone();
+ }
+ let mut groups: Vec<([u8; 3], Vec)> = vec![];
+ for (path, color) in outlines {
+ match groups.iter_mut().find(|(c, _)| *c == color) {
+ Some((_, paths)) => paths.push(path),
+ None => groups.push((color, vec![path])),
+ }
+ }
+ let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
+ }
+
+ /// How many outlines there are, in every color.
+ pub fn len(&self) -> usize {
+ self.groups.iter().map(|(_, paths)| paths.len()).sum()
+ }
+
+ /// Whether there is no outline.
+ pub fn is_empty(&self) -> bool {
+ self.groups.iter().all(|(_, paths)| paths.is_empty())
+ }
+}
+
/// A Global Edit in progress (per document; not saved, not an undo step).
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
@@ -202,7 +247,7 @@ pub struct GlobalEdit {
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
- outlines: std::cell::RefCell